Search code examples
asp.net-mvc-4viewmodelactionmethod

HttpPost action method recalled when the view presented by it is reloaded


I have an HTTPPOST action method that receives a model and saves it to the database:

[HttpPost]
public ActionResult AddDocument(Document doc){
   DocumentRepository repo= GetDocumentRepository();
   repo.SaveDocument(doc);
   return View(viewName: "DocViewer", model: doc);
}

So this method receives the model, saves it and then returns it to the DocViewer view to display the added document. I have two problems including the one in the question

  1. If I press F5 after the DocViewer is presented I get a warning that the post method will be invoked again. How do I avoid this? I'm sure there's a general practice
  2. In the DocViewer view I have defined HTML elements like this:
<div>Full name</div>
<div>@Html.LabelFor(x=>x.FullName)</div> 
<div>Address</div>
<div>@Html.LabelFor(x=>x.Address)</div> //and so on

But what I get is the following output:

Full name FullName
Address Address

Shouldn't I get the actual value but not the property name (or the Display Name if it's provided)?


Solution

  • In Post action do not return model object back to view:

    [HttpPost]
    public ActionResult AddDocument(Document doc)
    {
       DocumentRepository repo= GetDocumentRepository();
       repo.SaveDocument(doc);
       //return View("DocViewer");
       TempData["Document"] = doc;
       return RedirectToAction("DocViewer","ControllerName");
    }
    

    and in DocViewer action:

    public ActionResult DocViewer()
    {
       Document doc = TempData["DocViewer"] as Document;
       return View(doc);
    
    }
    

    UPDATED:

    you have to redirect to DocViewer view via its action to avoid form post again if F5 pressed.

    See details here