Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent EnumDropDownListFor set 0 as optionLabel value?

I have an enum dropdown:

@Html.EnumDropDownListFor(model => model.Type, "-- Choose --", new { @class = "postfix" })

and html code generated for enum dropdown is:

<select data-val="true" data-val-required="Select type of ..." id="Type" name="Type" class="valid">
    <option selected="selected" value="0">-- Choose --</option>
    <option value="1">‌Hotel</option>
    <option value="2">Flight</option>
</select>

I don't want optionLabel's value be 0 because this value make dropdown valid and no error message will be displayed. how can I prevent this ?

like image 810
Mohsen Esmailpour Avatar asked Dec 12 '22 05:12

Mohsen Esmailpour


1 Answers

I know it's old, but just in case someone stumbles across this question as I did, here is a valid workaround.

Instead of using EnumDropDownListFor, use the standard DropDownListFor with an EnumHelper:

@Html.DropDownListFor(model => model.Type, EnumHelper.GetSelectList(typeof(yourNamespace.yourType)), "-- Choose --", new { @class = "postfix", @required = "required" })

This will give the desired output. I also added @required = "required" which will provide native HTML validation within supported browsers.

like image 183
dboswell Avatar answered Dec 13 '22 17:12

dboswell