Jac*_*ack 3 asp.net-mvc field clear razor asp.net-mvc-4
What is the most effective method in order to make all the fields on an MVC4 Razor empty when loading it (for example first loading or after backing to the page again)? If it is possible could you please suggest me a way with the help of Razor properties instead of using Javascript/jQuery.
Joh*_*n H 12
要弄清楚你想要做什么有点困难,但让我们看看我是否可以提供帮助.
首先,如果您只想在发布后清除表单的值,您可以这样做:
[HttpPost]
public ActionResult Index(ViewModel model)
{
ModelState.Clear();
model = new ViewModel();
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
仅仅创建一个新的ViewModel
是不够的,因为ModelState
字典将尝试使用旧值重新填充表单.这可以满足您的需求,但并不是真正利用MVC来做您想做的事情.
更好的方法是重定向回用于显示表单的操作.像这样的东西:
public ActionResult Create()
{
var model = new ViewModel();
return View(model);
}
Run Code Online (Sandbox Code Playgroud)
这只是将一个空模型传递给您的表单.一旦用户填写表单并将其发回服务器,您就可以像这样处理它:
[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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
15759 次 |
最近记录: |