Html.DropDownListFor does not bind boolean SelectL

2019-08-10 20:44发布

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条回答
Emotional °昔
2楼-- · 2019-08-10 21:21

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)
查看更多
登录 后发表回答