I am wanting to use the @Html.EnumDropDownListFor and I'm having an issue.
This is what I have:
@Html.EnumDropDownListFor(x => x.DefaultProviderEnum,
"Select default provider", new { @class = "form-control", id = "pro" })
Where DefaultProviderEnum is of type ProviderFormat:
public enum ProviderFormat
{
[Description("ASG")]
ASG = 1,
[Description("SCS")]
SCS = 2
}
And I set it correctly in the model and it appears correctly when it loads. The issue that I have is when I post it I have to manually set it in my object instead of it binding to a property on my object, which is an int:
model.CU.DefaultProviderInt = (int)model.DefaultProviderEnum;
Is there a way to bind the enum drop down to a property on an object and not have to set it this way?
model.CUobject will also get bound (binded?) by theModeBinderwith whatever value has been provided on submit of the form.So, in your form, you can have a hidden property like this:
Then add a
changeevent handler to theDefaultProviderEnumdropdown and set hidden input's value with theselectvalue.Now when the form gets submitted, both the properties will have the same value.
There's another way to do this. The above code won't work if you manually set the value of
DefaultProviderEnumsomewhere in your code. So, you can have a custom setter for theDefaultProviderEnumproperty:But, this also might depend on the order in which
DefaultModelBinderbinds properties. (IfCUis null whenDefaultProviderEnumis being set, then this might not work. So make sure to initCUin model's constructor)The third and the best way to do this is to manually cast the enum to int and set it to
CU.DefaultProviderInt.