ASP.NET MVC: DropDownList validation

2019-04-12 23:09发布

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条回答
Root(大扎)
2楼-- · 2019-04-12 23:12
new SelectListItem {Text = "Unknown", Value = "null"},

should be:

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

Posting "" will result in null being bound.

查看更多
登录 后发表回答