MVC验证和错误处理周期
本文关键字:处理 周期 错误 验证 MVC | 更新日期: 2023-09-27 18:11:49
我有两个动作方法在一个控制器,
指数:
public ActionResult Index(string url)
{
// take the url as a param and do long tasks here
ViewBag.PageTitle = "title";
ViewBag.Images = "images";
// and some more view bags
return View();
}
这个索引视图包含一个表单,该表单发送到同一控制器中的另一个方法。
public ActionResult PostMessage(string msg, string imgName)
{
// save data in the db
// but on error I want to navigate back to the Index view but without losing data the user fielded before submit the form.
// Also need to pass an error message to this index view to show
}
如果在PostMessage方法中出现问题,如何返回到索引视图,也不清除表单字段,并显示PostMessage方法指定的错误消息。
我需要知道做这种场景的最佳实践
最好的方法通常是为表单创建一个ViewModel类型。向该模型的属性添加属性,以定义什么会使其"错误"。让您的表单使用像@Html.TextBoxFor
这样的方法来处理各个字段。然后让PostMessage类接受该类型的对象,而不是直接接受消息和图像名称。然后,您可以验证模型,并在模型无效时再次返回视图。
请参阅http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx获取遵循此模式的一些代码示例。
您可以指定要返回的视图的名称:
public ActionResult PostMessage(string msg, string imgName)
{
if (SomeErrorWhileSavingInDb)
{
// something wrong happened => we could add a modelstate error
// explaining the reason and return the Index view.
ModelState.AddModelError("key", "something very wrong happened when trying to process your request");
return View("Index");
}
// everything went fine => we can redirect
return RedirectToAction("Success");
}
直接重定向到Index操作
return RedirectToAction("Index");