1)临时数据
允许您存储在重定向后仍可保留的数据。在内部,它使用 Session 作为后备存储,在进行重定向后,数据会自动被驱逐。模式如下:
public ActionResult Foo()
{
// store something into the tempdata that will be available during a single redirect
TempData["foo"] = "bar";
// you should always redirect if you store something into TempData to
// a controller action that will consume this data
return RedirectToAction("bar");
}
public ActionResult Bar()
{
var foo = TempData["foo"];
...
}
2)ViewBag、ViewData
允许您将数据存储在将在相应视图中使用的控制器操作中。这假定该操作返回一个视图并且不重定向。仅在当前请求期间存在。
模式如下:
public ActionResult Foo()
{
ViewBag.Foo = "bar";
return View();
}
在视图中:
@ViewBag.Foo
或使用 ViewData:
public ActionResult Foo()
{
ViewData["Foo"] = "bar";
return View();
}
在视图中:
@ViewData["Foo"]
ViewBag 只是ViewData 的动态包装器,仅存在于 ASP.NET MVC 3 中。
话虽如此,这两种构造都不应该被使用。您应该使用视图模型和强类型视图。所以正确的模式如下:
查看模型:
public class MyViewModel
{
public string Foo { get; set; }
}
行动:
public Action Foo()
{
var model = new MyViewModel { Foo = "bar" };
return View(model);
}
强类型视图:
@model MyViewModel
@Model.Foo
在这个简短的介绍之后,让我们回答你的问题:
我的要求是我想在控制器中设置一个值,即
控制器将重定向到 ControllerTwo 和 Controller2 将呈现
视图。
public class OneController: Controller
{
public ActionResult Index()
{
TempData["foo"] = "bar";
return RedirectToAction("index", "two");
}
}
public class TwoController: Controller
{
public ActionResult Index()
{
var model = new MyViewModel
{
Foo = TempData["foo"] as string
};
return View(model);
}
}
以及对应的视图(~/Views/Two/Index.cshtml):
@model MyViewModel
@Html.DisplayFor(x => x.Foo)
使用 TempData 也有缺点:如果用户在目标页面上按 F5,数据将会丢失。
我个人也不使用 TempData。这是因为它在内部使用 Session 并且我在我的应用程序中禁用了会话。我更喜欢一种更 RESTful 的方式来实现这一点。即:在执行重定向的第一个控制器操作中,将对象存储在您的数据存储中,并在重定向时使用生成的唯一 ID。然后在目标操作上使用此 id 取回最初存储的对象:
public class OneController: Controller
{
public ActionResult Index()
{
var id = Repository.SaveData("foo");
return RedirectToAction("index", "two", new { id = id });
}
}
public class TwoController: Controller
{
public ActionResult Index(string id)
{
var model = new MyViewModel
{
Foo = Repository.GetData(id)
};
return View(model);
}
}
视图保持不变。