validating radio buttons in a controller rather than the model requires a ValueProviderResult to be set explicitly

Catchy title to this little post! If you are validating a radio button and the user has not selected any radio buttons in the group then you will get an error if you use ModelState.AddModelError(“radiobuttonname”,”my error message”) unless you explicitly use ModelState.SetModelValue and pass in a ValueProvierResult as the model binder doesn’t like the null when it binds the view.
e.g.

ModelState.AddModelError(“gender”, “Please select male or female.”);
ValueProviderResult vpr = new ValueProviderResult(null, “”, null);
ModelState.SetModelValue(“gender”, vpr);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s