How to change the “required” attribute for view models in .net mvc

I was pulling my hair out one day wondering how I could make required attributes optional programmatically.

I wanted to make a questionnaire form where different questions were presented to users but using the one viewmodel and ui page for easy updating.

I finally solved it by doing the following.

Assume for the purpose of example that you have various required properties you don’t want to be validated.

I’ve put them in a string array for this example.

string[] arr1 = new string[] { “SchoolName”, “AddressLine1”, “AddressLine2”, “DesignSoftwareUsed”, “Documentation_IsTheTeamDocumentingDesign” };

foreach (var validator in ModelState)
if (arr1.Contains(validator.Key))

As you need to do on the postback controller is to clear the appropriate validation key value.

It’s really that simple.

That covers the backend but I’m sure there are those out there that are wondering about the frontend?

All you do is apply logic to show or hide the appropriate questions and job done.

Tagged with: , , ,
Posted in Mad ramblings

Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s

%d bloggers like this: