为了在加载 MVC4 Razor 时将其上的所有字段设为空(例如第一次加载或再次返回页面后),最有效的方法是什么?如果可能的话,请您在 Razor 属性的帮助下向我建议一种方法,而不是使用 Javascript/jQuery。
最佳答案
弄清楚您要做什么有点困难,但让我们看看我是否可以提供帮助。
首先,如果您只是想在表单发布后清除表单的值,您可以这样做:
[HttpPost]
public ActionResult Index(ViewModel model)
{
ModelState.Clear();
model = new ViewModel();
return View(model);
}
只需新建一个
ViewModel
还不够,因为ModelState
字典将尝试用旧值重新填充表单。这可以满足您的需求,但并没有真正利用 MVC 来做您想做的事情。更好的方法是重定向回用于显示表单的操作。像这样的东西:
public ActionResult Create()
{
var model = new ViewModel();
return View(model);
}
这只是将一个空模型传递给您的表单。一旦用户填写了表单并将其发送回服务器,您就可以像这样处理它:
[HttpPost]
public ActionResult Create(ViewModel model)
{
if (ModelState.IsValid)
{
// Form data is valid so redirect back to display the form again
return RedirectToAction("Create");
}
// If we get here, redisplay the form with the fields filled in
// and errors shown
return View(model);
}
关于asp.net-mvc - 清除 MVC 4 Razor View 中的所有字段 : Loading and after Back to Page,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19659048/