In my view I have a enumdropdownlist (a new feature in Asp.Net MVC 5.1).
@Html.EnumDropDownListFor(m => m.SelectedLicense,new { @class="form-control"})
If I execute the above code I get dropdownlist for my following enum.
public enum LicenseTypes
{
Trial = 0,
Paid = 1
}
but by default I want my dropdownlist to have a value(custom text) and this is what I tried
@Html.EnumDropDownListFor(m => m.SelectedLicense,"Select a license" ,new { @class="form-control"})
but now the problem is when i run it, my dropdownlist looks like this So, the default text I want to show doesn't appear by default. If a user selects "select a license" and tries to submit the form, it does show an error saying "select a license" but it doesn't show as default text. Something i need to change?
Ps: The image is the screenshot of the page when it loads. By default it'll show Trial as selected option.
Try to change the
Index
ofLicenseTypes
start from1
not0
like below:Then you can use
Range attribute
to validate the selected license type like below:Finally, in your view:
Am I a bit late ?
Changing the values of the enum type is not very satisfying.
Neither is changing the model property to render it nullable and then add a [Required] attribute to prevent it to be nullable.
I propose to use the ViewBag to set the default selected value of the dropdown. The line 4 of the controller just bellow is the only important one.
EDIT : Ah... newbies... My first idea was to use ModelState.SetModelValue because my newbie instinct prevented me to simply try to set the desired value in the ViewBag since the dropdown was binded to the model. I was sure to have a problem: it would bind to the model's property, not to the ViewBag's property. I was all wrong: ViewBag is OK. I corrected the code.
Here is an example.
Model:
Controller:
View:
Without the "ModelState.SetModelValue or ViewBag.FavouriteMusic = string.Empty" line in the model Index action the default selected value would be "Metal" and not "Select your music..."
I have an enum:
In my model I have:
An in the view:
By this I have a dropdown with default option "Select sex", but validation accepts only options provided by enum ("Male" and "Female").
In MVC3 (without EnumDropDownListFor) I used in model:
In view:
By the time your
EnumDropDownListFor
is renderedSelectedLicense
already has the default value for the type, which is0
.Just change the type of your
SelectedLicense
property to a nullable enum, like so:This also allows you to continue using the
Required
attribute, which I think is significantly cleaner. TheRequired
attribute will not allow a null response, so even though your model allows nulls, the form will not.The ViewModel class needs to have the default value set on the enum property for it to be the default selected public
Controller:
View: