Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I pass an enum into a controller so the Model Binder binds it?

if so, how should i pass the parameter? would a string matching the enum name be ok? This would be handy if I was passing a dropdown box that matched enumerated items.

It would be useful to use a solution presented in this answer if I could just as easily bind to the enum when I submit the data back.

like image 313
DaveDev Avatar asked Aug 06 '10 11:08

DaveDev


2 Answers

It gets even better you can also pass Enum as get parameter

@Html.ActionLink("Email Quote", "UnitDetails", "Journey", new { product = product.ProductTitle, button = "email" }, new { @class = "btn btn--main btn--main-orange" })

that ends up following url: http://localhost:50766/UnitDetails?product=Your%20quote&button=email

Action method that accepts looks like this:

    [SessionTimeout]
    public ActionResult UnitDetails(QuoteViewModel viewModel)

QuoteViewModel and enum:

public class QuoteViewModel : IQuoteViewModel
{
    public QuoteViewModelProducts Products { get; set; }

    public bool HasDiscount { get; set; }

    public string Product { get; set; }

    public DetailButtonType Button { get; set; }
}

public enum DetailButtonType
{
    Buy,
    Callback,
    Email
}

What I love most is even if you pass enum parameter and value as lowercase it maps correctly to Uppercase property and Value, which makes my grin profusely.

enter image description here

like image 101
Matas Vaitkevicius Avatar answered Oct 19 '22 23:10

Matas Vaitkevicius


Yes, when having a controller like:

enum MyAction { Lalala }

public ActionResult Index(MyAction action) { ... }

You can just do Index/Lalala, and everything works fine.

If you need more complex binding (like mapping a certain string value to a complex class), use something like StructureMap.

like image 30
Jan Jongboom Avatar answered Oct 19 '22 23:10

Jan Jongboom