I think my question is a common scenario because I've been reading about these hours but to be honest I still have some doubts about it. I have a simple controller with these actions (as far as I understood this follows the PRG pattern)
public ActionResult Index()
{
var partyId = (int) Session["PartyId"];
var viewModel = _displayBuilder.Build(partyId);
return View(viewModel);
}
[HttpGet]
public ActionResult AddDocument()
{
var partyId = (int) Session["PartyId"];
var viewModel = _createBuilder.Build(partyId);
return PartialView("_AddDocument", viewModel);
}
[HttpPost]
public ActionResult AddDocument(AddDocumentViewModel viewModel)
{
var partyId = (int)Session["PartyId"];
if (ModelState.IsValid)
{
_documentsManager.AddDocument(viewModel, partyId);
return RedirectToAction("Index");
}
var newViewModel = _createBuilder.Rebuild(viewModel, partyId);
return PartialView("_AddDocument", newViewModel);
}
And the Index view holds this inside it
<div id="addDocument">
@{ Html.RenderAction("AddDocument"); }
</div>
plus a list of documents.
Problem is when the server validation fails, as it displays only the partialview as it's stated in the post method. I would like to be able to display the index view but without losing the form state (including modelstate, I guess I could pass this in the TempData but anyway I would lose the field's values posted).
As far as I can think there are some things I can do.
- Put everything in the same view
- Do the opposite to what I'm doing and create the list of documents as the partial view.
- Create the form as an ajax one. Not really sure about this one.
Is there anything I'm missing?
I was thinking of keeping this page the less "clever" I could and thus avoiding ajax for the moment, I would definitely go for it if it's clear is the best solution though. I think with that I could still maintain the form in a partial view and reuse it for another views. I mean two partials, the view and the list for updating it, is this right?
Thanks