可以使用TempData在重定向期间传递数据。TempData使用Session来存储数据,但数据只会在第一次读取后被删除,这使得它非常适合用于重定向数据。
例如,若要从HomeController的方法传递参数到Index方法并重定向到Index视图:
HomeController.cs:
public ActionResult RedirectWithParameters()
{
string parameterValue = "myValue";
TempData["myParameter"] = parameterValue;
return RedirectToAction("Index");
}
Index方法:
public ActionResult Index()
{
string myParamValue = TempData["myParameter"] as string;
if (myParamValue != null)
{
ViewBag.MyParameter = myParamValue;
}
return View();
}
在Index视图中,您可以访问 ViewBag.MyParameter 变量来获取传递过来的值:
Index.cshtml:
My parameter value is: @ViewBag.MyParameter