Benjamin RD
Benjamin RD

Reputation: 12034

Add ModelState.AddModelError without reload the page (mvc4)

I'm using MVC4 and I have 2 methods in my controller:

Get Method

public ActionResult Create()
{
    var vm = new User
    {
        Client= new Catastro_Cliente()
        Genre = ClienteRepository.GetGenres(),
        Type= ClienteRepository.GetTypes()
    };

    ViewBag.Genre = new SelectList(vm.Genre, "IdGenre", "Genre");
    ViewBag.Type= new SelectList(vm.Type, "IdType", "Type");
    return View(vm);
}

Post Method

[HttpPost]
public ActionResult CrearUsuario(Catastro_Cliente client)
{
    if(Validator(client.document))
    {
        ModelState.AddModelError("NoDocument", "The document is invalid or not registered");
    }

    if(ModelState.IsValid)
    {
        return View();
    }
}

Basically, I'm trying keep all the data that the user filled in before the post Method,

I tried with return RedirectToAction("Create"); but it always refreshes the page.

Upvotes: 0

Views: 830

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239250

You have to pass back the posted model when you call View. What you need is something like:

[HttpPost]
public ActionResult CrearUsuario(Catastro_Cliente client)
{
    if(Validator(client.document))
    {
        ModelState.AddModelError("NoDocument", "The document is invalid or not registered");
    }

    if(ModelState.IsValid)
    {
        // save to database of whatever
        // this is a successful response
        return RedirectToAction("Index");
    }

    // There's some error so return view with posted data:
    return View(client);
}

Upvotes: 1

Related Questions