TheRRRanger
TheRRRanger

Reputation: 365

Retaining failed validation data

I've got a requirement to keep and display an incorrect entry on the view. It isn't possible to go to the next page without passing all validation.

For example, the use has to enter a date in text field in a certain format. Currently if the model binding fails it doesn't keep the invalid date text entry. I'd like to keep t and display it back to user with a vanadium failed message.

I'd like to know if this is achievable without creating a data holder type which temporarily hold the entered game and parsed value.

Upvotes: 0

Views: 47

Answers (1)

HTX9
HTX9

Reputation: 1717

Yes, it is possible. Because you haven't posted any code, I'll just give you an example of how this can be achieved using server side validation.

Here is the [HttpGet] action method that serves up the form allowing the user to enter data.

[HttpGet]
public ActionResult Create()
{
    // The CreateViewModel holds the properties and data annotations for the form
    CreateViewModel model = new CreateViewModel();
    return View(model);
}

Here is the [HttpPost] action method that receives and validates the form.

[HttpPost]
public ActionResult Create(CreateViewModel model)
{
    if (!ModelState.IsValid)
    {
        return Create(); // This will return the form with the invalid data
    }

    // Data is valid, process the form and redirect to whichever action method you want

    return RedirectToAction("Index");
}

You can also use return View(model); in the [HttpPost] action method instead of return Create();.

Upvotes: 2

Related Questions