0

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.

  1. Put everything in the same view
  2. Do the opposite to what I'm doing and create the list of documents as the partial view.
  3. 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

4

1 回答 1

0

如果不使用 Ajax,我真的看不到任何解决方法,因为您将结果呈现为“新”页面。

我能真正想到的唯一方法是重新加载完整的“索引”以及部分视图,但在这种情况下,使用 ajax 会容易得多。

像这样的东西:

$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    data: data,
    dataType: "html",
    success: function (data) {
        $("#addDocument").html(data);
    }
});

而不是使用

@{ Html.RenderAction("AddDocument"); }

利用

@Html.Partial("_AddDocument")

希望这可以帮助。

于 2013-04-24T06:50:00.180 回答