Reputation: 5105
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.
Upvotes: 0
Views: 67
Reputation: 4793
Is your model Disability
bool property nullable
?
because if not, the default value of Disability
is false
and this:
@Html.DropDownListFor(model => model.Disability, Model.DisabilityList)
will selected the value associated to false
, which is No
.
Upvotes: 2
Reputation: 95
this
new SelectList(_listService.YesNoList(), "Value", "Text", "");
should be something like this
new SelectList(_listService.YesNoList(), "Value", "Text", _listService.YesNoList().First());
Upvotes: 0