enum args in controller action methods?

Last post 06-26-2009 12:22 PM by Haacked. 2 replies.

Sort Posts:

  • enum args in controller action methods?

    06-26-2009, 11:08 AM
    • Member
      2 point Member
    • skmcfadden
    • Member since 02-02-2009, 9:10 PM
    • Posts 25

    Is it possible use an enum argument in a controller action method?   How would javascript represent an enum arg value when calling a controller action?



    thanks!

    Filed under:
  • Re: enum args in controller action methods?

    06-26-2009, 11:41 AM
    • Contributor
      6,620 point Contributor
    • paul.vencill
    • Member since 02-01-2006, 12:57 PM
    • Gaithersburg, MD
    • Posts 1,350

     I've done it as a member property of an object that is getting model bound, so the DMB can definitely do it that way (in that case, I represented the enum as a dropdownlist).  NOt sure if it would work on its own.  going from JS might be more complex; I'll have to think about it.

    Help those who have helped you... remember to "Mark as Answered"
  • Re: enum args in controller action methods?

    06-26-2009, 12:22 PM
    Answer
    • Contributor
      5,773 point Contributor
    • Haacked
    • Member since 09-17-2003, 2:43 PM
    • Posts 388
    • AspNetTeam

    Yes, it is possible. You can submit either the integer value or the string name of the enum value. A quick experiment verifies this. For example, in HomeController.cs write this.

        public class HomeController : Controller {
            public ActionResult Index() {
                return View();
            }
    
            [AcceptVerbs(HttpVerbs.Post)]
            public ActionResult Index(MyEnum value) {
                ViewData["Message"] = value.ToString();
    
                return View();
            }
        }
    
        public enum MyEnum { 
            Foo,
            Bar,
            Baz
        }


    Then in Index.aspx include the form:

        <% using (Html.BeginForm()) { %>
            <%= Html.TextBox("value") %>
            <input type="submit" />
        <% } %>

    And try submitting the value 0 then try submitting Bar and you'll see they both work.

    Phil 

    Phil Haack (http://haacked.com/)
    Senior Program Manager, Microsoft

    What wouldn’t you do for a Klondike bar?
Page 1 of 1 (3 items)