使用ASP.NET MVC可能需要一些情况(例如表单提交)RedirectToAction.
其中一种情况是,您在表单提交后遇到验证错误并需要重定向回表单,但希望URL反映表单的URL,而不是它提交的操作页面.
由于我要求表单包含最初POST编辑的数据,为了方便用户和验证目的,我如何通过RedirectToAction()?如果我使用viewData参数,我的POST参数将更改为GET参数.
我有以下两种操作方法(简化问题):
[HttpGet]
public ActionResult Create(string uniqueUri)
{
// get some stuff based on uniqueuri, set in ViewData.
return View();
}
[HttpPost]
public ActionResult Create(Review review)
{
// validate review
if (validatedOk)
{
return RedirectToAction("Details", new { postId = review.PostId});
}
else
{
ModelState.AddModelError("ReviewErrors", "some error occured");
return RedirectToAction("Create", new { uniqueUri = Request.RequestContext.RouteData.Values["uniqueUri"]});
}
}
Run Code Online (Sandbox Code Playgroud)
因此,如果验证通过,我将重定向到另一页(确认).
如果发生错误,我需要显示包含错误的同一页面.
如果我这样做return View(),则会显示错误,但如果我这样做return RedirectToAction(如上所述),则会丢失模型错误.
我对这个问题并不感到惊讶,只是想知道你们是怎么处理这个问题的?
我当然可以返回相同的View而不是重定向,但我在"Create"方法中有逻辑,它填充了视图数据,我必须复制它.
有什么建议?
error-handling asp.net-mvc redirecttoaction modelstate http-redirect
如果我的ModelState中存在错误而不丢失我的ModelState信息,如何返回不同操作的结果或将用户移动到其他操作?
情景是; 删除操作接受由我的索引操作/视图呈现的DELETE表单中的POST.如果删除中出现错误,我想将用户移回索引操作/视图,并显示删除操作存储的错误ViewData.ModelState.如何在ASP.NET MVC中完成?
[AcceptVerbs(HttpVerbs.Post | HttpVerbs.Delete)]
public ActionResult Delete([ModelBinder(typeof(RdfUriBinder))] RdfUri graphUri)
{
if (!ModelState.IsValid)
return Index(); //this needs to be replaced with something that works :)
return RedirectToAction("Index");
}
Run Code Online (Sandbox Code Playgroud)