2

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 Answer 1

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

should be:

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

Posting "" will result in null being bound.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot, I never would have been able to figure that out. Did you learn this by trial and error or can I find that information somewhere? It seems that "go-to resources" are pretty scarce when it comes to ASP.NET MVC.
Nope, never read about that, made sense to me. I think I first noticed it leaving input type=texboxs empty. The model binder always bound the string fields to null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.