Html.DropDownListFor does not bind boolean SelectList

泪湿孤枕 提交于 2020-01-05 08:09:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!