dcg
dcg

Reputation: 4219

How to clear a form after an insert?

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!

Upvotes: 0

Views: 123

Answers (1)

Renato Leite
Renato Leite

Reputation: 791

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)
    }

Upvotes: 3

Related Questions