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.
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.
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.
精彩评论