ASP.NET MVC: DropDownList validation

谁说胖子不能爱 提交于 2019-12-06 11:20:14

问题


Note: The following is just an example.

I'm pretty new to ASP.NET MVC and I'm trying to get my head around how validation of dropdown lists work. I have the following property in my ProfileViewModel class:

[DisplayName("Gender")]
public bool? Gender { get; set; }

null is meant to mean "unknown", true female and false male. In the view model constructor I

AllGenders = new List<SelectListItem>(2)
             {
                 new SelectListItem {Text = "Unknown", Value = "null"},
                 new SelectListItem {Text = "Male", Value = "false"},
                 new SelectListItem {Text = "Female", Value = "true"}
             };

First of all, it seems that I have to use strings when populating a List<SelectListItem>, which feels kinda weird. Is this really how it's done?

Secondly, when I choose "Unknown" in the list the validation fails telling me:

The value 'null' is not valid for Gender.

Why is that? When I remove the "null" option and change Gender to a simple bool, everything seems fine.

This is the ASPX:

<%= Html.DropDownList("Gender", Model.AllGenders) %>

(I can't get DropDownListFor to work correctly and it seems that many others have the same problem.)

Any help appreciated!


回答1:


new SelectListItem {Text = "Unknown", Value = "null"},

should be:

new SelectListItem {Text = "Unknown", Value = ""},

Posting "" will result in null being bound.



来源:https://stackoverflow.com/questions/3628066/asp-net-mvc-dropdownlist-validation

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