blank option @htm.Enumdropdownlistfor MVC5

Asked

Viewed 32 times

1

I’m having a problem in my Razor, I want the option that comes selected is a blank. my Razor is like this:

 @Html.EnumDropDownListFor(m => m.Endereco.Zona, string.Empty ,new { @class = "form-control-sm", style = "height: 20px;padding: 0;width: 156px" })

I tried it like this too:

 @Html.EnumDropDownListFor(m => m.Endereco.Zona,"Selecione" ,new { @class = "form-control-sm", style = "height: 20px;padding: 0;width: 156px" })

but anyway, it is always selected option 0. the HTML it generates stays that way:

     <select class="form-control-sm valid">
   <option value=""></option>
    <option selected="selected" value="0">Norte</option>
    <option value="1">Sul</option>
    <option value="2">Sudeste</option>
    <option value="3">Nordeste</option>
    <option value="4">CentroOeste</option>
    </select>

I realized that an option comes with a Selected option:

<option selected="selected" value="0">Norte</option>

Does anyone know how I can change that?

1 answer

2


Just change the type of your Enum Zona in an annulable Enum, as follows:

public Zona? Zona { get; set; }

This also allows you to use Required in the attribute, which I think is significantly cleaner. Required in the attribute will not allow a null answer, so even if your model allows nulls, the form will not.

  • perfect friend... thank you very much... a little something nothing, made me hit my head ora caramba!!!

  • I’m glad it worked out, it happens, I’ve been there too.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.