How to RedirectToAction in ASP.NET MVC without losing request data

Using ASP.NET MVC there are situations (such as form submission) that may require a RedirectToAction.

One such situation is when you encounter validation errors after a form submission and need to redirect back to the form, but would like the URL to reflect the URL of the form, not the action page it submits to.

As I require the form to contain the originally POSTed data, for user convenience, as well as validation purposes, how can I pass the data through the RedirectToAction()? If I use the viewData parameter, my POST parameters will be changed to GET parameters.

91937 次浏览

解决方案是使用 TempData 属性存储所需的 Request 组件。

For instance:

public ActionResult Send()
{
TempData["form"] = Request.Form;
return this.RedirectToAction(a => a.Form());
}

然后在你的“形式”动作中,你可以这样做:

public ActionResult Form()
{
/* Declare viewData etc. */


if (TempData["form"] != null)
{
/* Cast TempData["form"] to
System.Collections.Specialized.NameValueCollection
and use it */
}


return View("Form", viewData);
}

请记住,TempData 在会话中存储表单集合。如果您不喜欢这种行为,可以实现新的 ITempDataProvider 接口,并使用其他一些机制来存储临时数据。我不会这样做,除非你知道一个事实(通过测量和分析) ,会话状态的使用正在伤害你。

还有一种避免临时数据的方法。我喜欢的模式包括为无效表单的原始呈现和重新呈现创建1个操作。大概是这样的:

var form = new FooForm();


if (request.UrlReferrer == request.Url)
{
// Fill form with previous request's data
}


if (Request.IsPost())
{
if (!form.IsValid)
{
ViewData["ValidationErrors"] = ...
} else {
// update model
model.something = foo.something;
// handoff to post update action
return RedirectToAction("ModelUpdated", ... etc);
}
}


// By default render 1 view until form is a valid post
ViewData["Form"] = form;
return View();

That's the pattern more or less. A little pseudoy. With this you can create 1 view to handle rendering the form, re-displaying the values (since the form will be filled with previous values), and showing error messages.

当发送到此操作时,如果其有效,则将控制权转移到另一个操作。

I'm trying to make this pattern easy in the . net 验证框架 as we build out support for MVC.

看看 MVCContrib,你可以这样做:

using MvcContrib.Filters;


[ModelStateToTempData]
public class MyController : Controller {
//
...
}

如果要将数据传递给重定向操作,可以使用的方法是:

return RedirectToAction("ModelUpdated", new {id = 1});
// The definition of the action method like  public ActionResult ModelUpdated(int id);

TempData is the solution which keeps the data from action to action.

Employee employee = new Employee
{
EmpID = "121",
EmpFirstName = "Imran",
EmpLastName = "Ghani"
};
TempData["Employee"] = employee;