【发布时间】:2014-03-03 08:20:48
【问题描述】:
您在提交表单后遇到验证错误的一种情况,您希望重定向回表单,但希望 URL 反映表单的 URL,而不是页面操作。
如果我使用 viewData 参数,我的 POST 参数将更改为 GET 参数。
如何避免? 我希望该选项未更改为 GET 参数。
【问题讨论】:
标签: c# asp.net-mvc-4
您在提交表单后遇到验证错误的一种情况,您希望重定向回表单,但希望 URL 反映表单的 URL,而不是页面操作。
如果我使用 viewData 参数,我的 POST 参数将更改为 GET 参数。
如何避免? 我希望该选项未更改为 GET 参数。
【问题讨论】:
标签: c# asp.net-mvc-4
正确的设计模式是在验证错误的情况下不重定向,而是再次呈现相同的表单。仅当操作成功时才应重定向。
例子:
[HttpPost]
public ActionResult Index(MyViewModel model)
{
if (!ModelState.IsValid)
{
// some validation error occurred => redisplay the same form so that the user
// can fix his errors
return View(model);
}
// at this stage we know that the model is valid => let's attempt to process it
string errorMessage;
if (!DoSomethingWithTheModel(out errorMessage))
{
// some business transaction failed => redisplay the same view informing
// the user that something went wrong with the processing of his request
ModelState.AddModelError("", errorMessage);
return View(model);
}
// Success => redirect
return RedirectToAction("Success");
}
此模式允许您保留所有模型值,以防发生某些错误并且您需要重新显示相同的视图。
【讨论】: