ASP.NET MVC ModelState ModelError

Suppose you have messed with the client validation via jquery unobstructive validation and now you cannot save your edited model since it does not POST any more.  Now, your objective is trying to find out which field is failing the validation.

1.  Turn off client validation by setting the following application setting:

<add key="ClientValidationEnabled" value="false" />

2.  At this point, you should be able to post the edited model.  In your controller method, you can verify the model’s valid state

// verify model is valid
if (ModelState.IsValid)

If it is false, then you can use the following code to detect which field is triggering a validation error.

#region Display any Model Error
foreach (var fieldname in this.ModelState.Keys.Where(key => this.ModelState[key].Errors.Count > 0))
Debug.Print("Model Field: {0} has an error [{1}].", fieldname, this.ModelState[fieldname].Errors[0].ErrorMessage);


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