lchong0412
lchong0412

Reputation: 1

MVC view model text data lost after the post, how to display them in the case of failed validation?

I've got a view model that has some text properties. And I use Html.DisplayFor to display them on the screen. But those text data won't be post back, so in the case of failed validation, the returned view won't have those data. How do I handle this kind of situation?

Thanks

Upvotes: 0

Views: 1820

Answers (3)

Jason Robertson
Jason Robertson

Reputation: 149

ViewModel Preservers the state of what the user attempted to enter so if you simply redisplay the view return View(); it will return with the errant data in it the Validation Summary if it is being used will then enumerate required fields that do are not correct.

Upvotes: 0

Neil T.
Neil T.

Reputation: 3320

You need to create a new instance of the view model, populate it with the values you want to redisplay in the form, and send it back to the view:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ProcessForm(FormCollection formValues)
{
    ...
    // Perform validation, sending error messages to ModelState
    ...
    if (!Model.IsValid)
    {
        AddressViewModel viewModel = new AddressViewModel
        {
            StreetAddress = formValues["StreetAddress"],
            City = formValues["City"],
            ...
        };

        return View(viewModel);
    }
}

Upvotes: 0

Alexander Taran
Alexander Taran

Reputation: 6725

you might add Html.HiddenFor() for every field that you want to be posted back

Upvotes: 2

Related Questions