How to disable validation before calling UpdateModel in MVC3 Controller

Go To StackoverFlow.com

1

I'm looking to enable "saving" of form data prior to submission.

I want users to be able to save form progress, even when the form is in an invalid state, and then come back to it at a later time.

Now, my only problem is that I want to be able to use UpdateModel method to update my model. However, as the form is potentially invalid or just partially complete, this will throw an error.

Is there a way to annotate the following method such that validation is ignored in the SAVE instance?

[HttpPost]
public ActionResult Save(Model values)
{
var model = new Model();
UpdateModel(model);
}

I want to save having to write a 1-1 mapping for the elements being saved - which is my fallback option, but isn't very maintainable.

2012-04-05 16:44
by dazbradbury


1

Give TryUpdateModel(model) a try, should fit your needs.

This won't throw an exception, and it will update the model and then return false if there are validation errors.

If you care about the errors, you check the ModelState in the false instance.

Hence, you can use it as so to always save changes:

[HttpPost]
public ActionResult Save(Model values)
{
var model = new Model();
TryUpdateModel(model);

model.saveChanges();

}
2012-04-05 18:05
by Adam Tuliper - MSFT
Thanks! Initially I thought TryUpdateModel(model) just returned false and did nothing. HOWEVER, it does still update the model. That was the part I was missing. Essentially, I want to suppress any validation errors, and now I can do that by just ignoring the return value from TryUpdateModel. Perfect - dazbradbury 2012-04-05 19:53
Be aware, if you have client-side validation enabled, then you won't be able to submit the form. You could, however, disable the validation prior to submitting in a "Save" button - Erik Funkenbusch 2012-04-06 00:12
@MystereMan - That's what I've already implemented. I simply do a form submission via ajax, and I can provide some visual feedback based on the response. This makes sure to ignore client-side validation, and allows saving of the form extremely simply. Validation will occur before any of the data is actually used, and any attempts at injection can be tested against - dazbradbury 2012-04-07 15:04
Ads