23 November 2009 9:22p Pacific

Wizards in ASP.Net MVC: being selective with ModelState

by Matt Sherman

So, there are many ways to skin the cat we called form validation. With a wizard-style application, it requires some nuance.

With ASP.Net MVC, a traditional way to do validation is to use ModelState. ModelState is a property on your controller where you can collect errors relating to your Model. For example, if a LastName property is required, you would do something like this:

And then, when deciding whether to commit the changes, you’ll test the IsValid property:

What I am trying to do, however, is create a “wizard”. A characteristic of a wizard is that you can move forward only if all the data is valid, but you can move back regardless. And, after moving back and continuing forward again, your data on the forward screens will have been preserved. (Observe this on the next wizard you use.)

The ModelState.IsValid approach above is a bit monolithic – progress can only be made if all the submitted data is valid. What I want to do is save data on the back button where it’s valid, but still allow the backward move even if it’s not all correct. Follow?

So I found a nice little way of doing this. First, I created an extension method on ModelState which allows me to test if a particular part of the ModelState is valid:

This allows me to selectively commit the valid data, while simply ignoring the bad stuff:

Hopefully the above will help.

I haven’t seen a lot of discussion of wizards in ASP.Net MVC. There was explicit support for this sort of thing in WebForms, but it’s a roll-your-own proposition in MVC. This is to be expected – the stateless nature of the web is not really made for wizards, and MVC is close to the metal.

Would love to see Microsoft thinking about this scenario in future versions.

Comments are closed

Tell others

TwitterTweet this page
Digg!Digg this page
TwitterAdd to Google Reader

Experimental! Let me know how it works for you.

Shorten this page's URL

Learn more about the TinyASP URL shortener

ASP.Net jQuery Controls

Implement jQuery effects using familiar ASP.Net server controls. Learn more...

Recent posts

Avoiding “magic strings” in jQuery, C# and ASP.net MVC

Alikewise learnings #1: DIY PR

Sherman’s law of prior knowledge, or, predicting the past

The busiest people at Apple right now…

When “infographics” jump the shark

HTTPS is the least of your problems

Stacking up

Beware the truth-tellers

more...  

About us

ClipperHouse.com is brought to you by Matt Sherman and Fernando Chilvarguer, among others. Contact us here.