I am trying to to create a simple drop down menu for my MVC 4 Razor View. I have a Service Class containing a method which returns the following
public List<SelectListItem> YesNoList()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Select", Value = "" });
items.Add(new SelectListItem { Text = "Yes", Value = "True" });
items.Add(new SelectListItem { Text = "No", Value = "False" });
return items;
}
I call this service method in my Controller
[AllowAnonymous]
public ActionResult Register()
{
RegisterModel model = new RegisterModel();
model.DisabilityList = new SelectList(_listService.YesNoList(), "Value", "Text", "");
return View(model);
}
Then return it to my Razor View
<div class="editor-label">
@Html.LabelFor(model => model.Disability, "Do you have a disability?")
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.Disability, Model.DisabilityList)
</div>
I would like the item named “Select” to be the selected option in my drop down menu, but it always selects the option “No” by default. Why is this?
I tried changing the SelectListItem to this
items.Add(new SelectListItem { Text = "Select", Value = "", Selected = True });
But still it selects “No” as the selected option.
A simple bit of coding I know, but I can’t get it working.
Please help.
Thanks.
Is your model
Disabilitybool propertynullable?because if not, the default value of
Disabilityisfalseand this:will selected the value associated to
false, which isNo.