在MVC3中提交数据库中的数据后如何清除模型 [英] How to Clear model after submit the data in database in MVC3
问题描述
我正在数据库中提交一些数据,提交后我想显示同一页面.但是我正在查看页面的文本框值不为空.
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.
但是仍然保留文本框值.请建议我在mvc3中提交后清除模型.
But still the textbox value is remain. please suggest me to clear the model after submit in 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);
}
推荐答案
您将获得相同的模型,因为您将其传递给视图View(model)
.您在这里有几个选择:要么传递一个空模型,要么重定向到您的post操作的get变体.
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.
1)
if (ModelState.IsValid)
{
//saving
if (result > 0)
{
ModelState.Clear();
return View(new CategoryViewModel());
}
}
2)
if (ModelState.IsValid)
{
//saving
if (result > 0)
{
return RedirectToAction("AddNewCategory");
}
}
PS:我强烈建议您使用第二种方法,因为您可能希望进行其他数据库调用来构建模型,并且您不想在多个地方这样做.
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.
这篇关于在MVC3中提交数据库中的数据后如何清除模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!