views:

41

answers:

3

I have a form that is going through some validation before sending an e-mail.

I have tried using this for validation, where the method ValidateInput sets the ModelState depending on the input:

[HttpPost]
public ActionResult Create(FormCollection collection)
{
    ValidateInput(collection);
    if (ModelState.IsValid == false) return View(collection);

This clears all the entered fields if something is invalid. I want to keep all the entered data in the field. How can I do that?

+1  A: 

AFAIK you wouldn't need to call ValidateInput yourself in the Create method - the framework has already set ModelState for you, so just remove the first line.

James Manning
A: 

If you can't change the ValidateInput method to not wipe your properties in this scenario then you'll really need two copies of the form data, one to pass to this method and one in reserve to pass to the view if validation fails.
You may be better off using a specific view model for the actions view rather than relying on the FormCollection object. That way you can use model binding to retrieve the data.
I think the code below should work but I haven't had a chance to test it so beware!

[HttpPost]
public ActionResult Create(MyCreateViewModel collection)
{
    MyCreateViewModel myCVM = new MyCreateViewModel();
    TryUpdateModel(myCVM);
    ValidateInput(myCVM);
    if (ModelState.IsValid == false) return View(collection);
Andy Rose
+3  A: 

Are you using Html helpers for input field in your form or regular html tags?

<%: Html.TextBoxFor(x => x.Message) %> - original value will be kept
<input type="text" name="Message" /> - original value will be lost after postback

Also you could benefit from using build-in validation (with data annotation attributes) instead of using your own validation method.

Koistya Navin