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.

1 Answer 1

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();

}
Sign up to request clarification or add additional context in comments.

3 Comments

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!
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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.