asp.net-mvc 在MVC3中提交数据库中的数据后如何清除模型
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27589005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Clear model after submit the data in database in MVC3
提问by Mukesh Kumar
I am submitting some data in database and after submit I want to show same page. But I am viewing the page the textbox value is not empty.
我正在数据库中提交一些数据,提交后我想显示相同的页面。但我正在查看页面,文本框值不为空。
ModelState.Clear();
ModelState.Clear();
I have used to clear the textbox.
我已经习惯清除文本框。
But still the textbox value is remain. please suggest me to clear the model after submit in mvc3.
但仍然保留文本框值。请建议我在 mvc3 中提交后清除模型。
public ActionResult AddNewCategory(CategoryViewModel model) {
if (ModelState.IsValid) {
int result = 0;
var categoryEntity = new Category {
CategoryName = model.CategoryName, CategorySlug = model.CategorySlug
};
result = Convert.ToInt32(_categoryRepository.AddNewCategory(categoryEntity));
if (result > 0) {
ModelState.Clear();
}
}
return View(model);
}
回答by Vsevolod Goloviznin
You're getting the same model, because you're passing it to the view View(model). You have couple options here: either pass an empty model, or redirect to the get variant of your post action.
您将获得相同的模型,因为您将其传递给 view View(model)。您在这里有几个选项:要么传递一个空模型,要么重定向到您的 post 操作的 get 变体。
1)
1)
if (ModelState.IsValid)
{
//saving
if (result > 0)
{
ModelState.Clear();
return View(new CategoryViewModel());
}
}
2)
2)
if (ModelState.IsValid)
{
//saving
if (result > 0)
{
return RedirectToAction("AddNewCategory");
}
}
PS: I strongly advice to use the second approach as you might want to make other DB calls to construct your model and you won't want to do this in multiple places.
PS:我强烈建议使用第二种方法,因为您可能希望进行其他数据库调用来构建您的模型,并且您不想在多个地方执行此操作。
回答by Qaiser
in very simplest way try it
以最简单的方式尝试一下
if(ModelState.IsValid)
{
//code here to save data to database
db.SaveChanges();
ModelState.Clear();
}
return view(new CategoryViewModel());
回答by asdf_enel_hak
Hear iswhat does ModelState.Clear()
听听是什么 ModelState.Clear()
ModelState.Clear() is used to clear errors but it is also used to force the MVC engine to rebuild the model to be passed to your View.
ModelState.Clear() 用于清除错误,但也用于强制 MVC 引擎重建模型以传递给您的视图。
So as in your case @Vsevolod Goloviznin suggested you can use:
因此,在您的情况下,@Vsevolod Goloviznin 建议您可以使用:
return View(new CategoryViewModel());
to have view with empty values
有空值的视图

