开发者

Html.DropDownListFor does not bind boolean SelectList

开发者 https://www.devze.com 2023-04-12 21:53 出处:网络
I have this code the constructs a select list as a boolean response var responseList = new List<SelectListItem>();

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开发者_StackOverflow社区 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?


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)
0

精彩评论

暂无评论...
验证码 换一张
取 消