Search code examples
c#asp.netasp.net-mvc-4html.dropdownlistfordropdownlistfor

MVC4 Set default SelectListItem in DropDownList when the list contains a SelecListItem with value 0


I am trying to set the default SelectListItem in my view to be ---Select---, with value null. This should be simple.

I know this can be done using this overload example in the view.

@Html.DropDownListFor(m=> m.SelectedId, M.List, "---Select---", null)

However, this is where I have a problem, this list I am trying to set the default on has a SelectListItem with value 0.

 @Html.DropDownListFor(model => Model.Vat, new List<SelectListItem>
                        {
                        new SelectListItem{Text = "Normal 20%", Value = "20"},
                        new SelectListItem{Text = "Reduced 5%",Value = "5"},
                        new SelectListItem{Text = "Exempt", Value = "0",} //This is the cause of the problem
                        }, "---Select---", null)

Now what happens is when my view loads, the ---Select--- option is at the top of the list with value null, as expected, however the default selected list item is "Exempt", from what I have gathered this is because MVC sets the default dropdownlist item to whatever option has the value 0.

I have tried many different workarounds to this, such as adding

new SelectListItem{Text = "Test", Value = null, Selected = true }

but this is still not selected when the page loads, and nothing else I have tried has worked.

I cant avoid having the option Exempt with value 0, as I need this information for my application.

I have searched and searched for an answer to this but found nothing helpfull, if anyone could point me in the right direction with how to approach this I would be very grateful.


Solution

  • Make the property nullable:

    public int? Vat { get; set;}

    The reason for this is that int has the default value of 0, so when your model is bound during a post, the value of your property will get set to 0 even if the selected value is null as int is not nullable but int? is.