by joe.pesch
25. June 2014 07:41
I was having difficulty binding a bool property to a DropDownList using the @Html.DropDownListFor() method. What ended up working well was to do the following:
Add this to the View Controller class:
private void Select_YN_Rebind()
{
List<SelectListItem> Select_YN = new List<SelectListItem>();
Select_YN.Add(new SelectListItem
{
Text = "No",
Value = bool.FalseString
});
Select_YN.Add(new SelectListItem
{
Text = "Yes",
Value = bool.TrueString
});
ViewData["Select_YN"] = Select_YN;
}
Add call to the new method in the View Controller Create method (or whatever other method is appropriate) before returning the view:
public ActionResult Create()
{
Select_YN_Rebind();
return View();
}
Call the @Html.DropDownListFor() as shown below:
@Html.DropDownListFor(model => model.YourBoolPropertyHere
, (IEnumerable<SelectListItem>)ViewData["Select_YN"])
66eaf84a-d822-4368-8d24-73b8d0253264|1|5.0|96d5b379-7e1d-4dac-a6ba-1e50db561b04
Tags:
ASP.Net | MVC