0

I have an action that creates a certain item to the data base, after doing that it will return the same view but with a newly created view model, something like:

MyItem i = new MyItem {...}
db.MyItems.Add(i);
db.SaveChanges();
ViewBag.Message = "Item added successfully";
return View(new MyItemViewModel());

I'm doing this 'cause several items might be inserted and going back and forward can be a little annoying. The above code works as expected, the thing is that the last information inserted remains in the form despite I'm giving the view a new view model without that information. I think this is browser related but I'm not sure. I'd like to know how can I get a clean form after the insertion of an item. Thanks in advance!

dcg
  • 4,187
  • 1
  • 18
  • 32
  • 2
    What about `ModelState.Clear();` after `ViewBag.Message`? – Salah Akbari Oct 04 '17 at 20:31
  • 3
    typically this is done by redirecting from the POST action to the GET action: `return RedirectToAction("ActionName")` – Sam Axe Oct 04 '17 at 20:32
  • @SamAxe That would do it! I've used several times the `RedirectToAction` except in this case lol. – dcg Oct 04 '17 at 20:37
  • @S.Akbari In fact the way you say is much better cause I can get to see the message which reminds me why I choose the statement `return View(new MyItemViewModel());`. Thanks. – dcg Oct 04 '17 at 20:44
  • For an explanation of the behavior, refer [this answer](https://stackoverflow.com/questions/26654862/textboxfor-displaying-initial-value-not-the-value-updated-from-code/26664111#26664111) - but the PRG pattern is the correct approach –  Oct 04 '17 at 20:57
  • @dcg: You can use `TempData` to transfer the message across redirects. – Sam Axe Oct 04 '17 at 21:42

1 Answers1

3

The correct way is redirect the request to the appropriate HttpGet action. In this mode you prevent data recess:

    [HttpPost]
    public ActionResult Save(MyViewModel formModel)
    {
        if (this.ModelState.IsValid)
        {
            // To save the message you will need to save in something like a tempdata, because they ViewBag will lost the value when the page redirect.
            TempData["myMessage"] = "My message.";

            // So you will clear your form and prevent data recess.
            return this.RedirectToAction("MyGETAction");
        }

        // You need to return the view here to show validation messages if you have.
        return View(formModel)
    }
Sam Axe
  • 33,313
  • 9
  • 55
  • 89
Renato Leite
  • 761
  • 1
  • 8
  • 28