如何在插入后清除表单?

时间:2017-10-04 20:25:54

标签: c# asp.net-mvc

我有一个动作可以为数据库创建一个特定的项目,之后它将返回相同的视图,但是使用新创建的视图模型,如:

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

我这样做会导致可能会插入多个项目并且前后移动可能会有点烦人。上面的代码按预期工作,事实是插入的最后一个信息仍保留在表单中,尽管我给视图一个没有该信息的新视图模型。我认为这与浏览器有关,但我不确定。我想知道如何在插入物品后获得干净的表格。提前谢谢!

1 个答案:

答案 0 :(得分:3)

正确的方法是将请求重定向到相应的HttpGet操作。在此模式下,您可以防止数据隐藏:

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