问题
I have this code the constructs a select list as a boolean response
var responseList = new List<SelectListItem>();
responseList.Add(new SelectListItem { Text = "Going", Value = bool.TrueString});
responseList.Add(new SelectListItem { Text = "Not Going", Value = bool.FalseString });
ViewData[ViewDataKeys.ResponseTo] = vatOptionList;
In my view I use the dropdownlist helper below.
@Html.DropDownListFor(m => m.ResponseTo, (IEnumerable<SelectListItem>)ViewData[ViewDataKeys.ResponseTo], "--Select--")
this is the property on my Model class:
[Display(Name = "Response To")]
public bool ResponseTo { get; set; }
My problem is that what ever the value of my model.ResponseTo is, the dropdownlist always select the optional value.
I tried to use a checkbox helper and surprisingly it doesn't appear to be checked alse, though when I inspected the element, the checkbox value is "true"
I tried to use a textbox helper and it shows a "true" text, Which I think that my model has value and it just doesn't bind to the dropdownlist or checkbox. I need to use a dropdownlist. Anything I missed out?
回答1:
Just tested this, it works:
In your action method:
var selectListItems = new List<SelectListItem>();
selectListItems.Add(new SelectListItem { Text = "Going", Value = bool.TrueString });
selectListItems.Add(new SelectListItem { Text = "Not going", Value = bool.FalseString });
ViewBag.MySelectList = new SelectList(selectListItems, "Value", "Text", viewModel.IsGoing);
In your view:
@Html.DropDownList("IsGoing", (SelectList) ViewBag.MySelectList)
来源:https://stackoverflow.com/questions/7750705/html-dropdownlistfor-does-not-bind-boolean-selectlist