现在,我正在做的是将tempdata传递给另一个动作时使用tempdata。
但是我的同事建议我不应该使用tempdata,因为他们在载荷之前对tempdata有经验的问题。
这是我的控制器的一部分,因此您可以看到我想做的事情。在不使用tempdata或会话的情况下,如何实现相同的过程。请建议,谢谢!
public ActionResult Create()
{
MyViewModel viewModel;
if (TempData["viewModel"] != null)
{
viewModel = (MyViewModel)TempData["viewModel"];
//code for getting dropdownlist to show to view
return View(viewModel);
}
viewModel = new RequestViewModel();
//code for getting dropdownlist to show to view
return View(viewModel);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MyViewModel viewModel)
{
if (ModelState.IsValid)
{
//collect data, but not yet save to database
TempData["viewModel"] = viewModel;
return RedirectToAction("Confirm");
}
//code to get errors, and dropdownlist items to re-show to view
return View(viewModel);
}
public ActionResult Confirm()
{
if (TempData["viewModel"] != null)
{
var viewModel = (MyViewModel)TempData["viewModel"];
return View(viewModel);
}
return RedirectToAction("Create");
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Confirm(MyViewModel viewModel)
{
if (ModelState.IsValid)
{
//save data to database if confirmed
return View(viewModel);
}
return RedirectToAction("Create");
}
- 编辑 -
我还尝试通过参数将ViewModel传递到重定向图,但我的ViewModel在重定向后没有重新播放。代码:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MyViewModel viewModel)
{
if (ModelState.IsValid)
{
//collect data, but not yet save to database
return RedirectToAction("Confirm", viewModel);
}
//code to get errors, and dropdownlist items to re-show to view
return View(viewModel);
}
public ActionResult Confirm(MyViewModel viewModel)
{
if (viewModel != null)
{
//some code
return View(viewModel);
}
return RedirectToAction("Create");
}
[HttpPost]
[ActionName("Review")]
[ValidateAntiForgeryToken]
public ActionResult ConfirmPost(MyViewModel viewModel)
{
if (ModelState.IsValid)
{
//save data to database if confirmed
return View(viewModel);
}
return RedirectToAction("Create");
}
假设页面加载的检查方法除了返回视图之外什么都不做,您不能使用
return View("Check", viewmodel);
您情况中的问题是由于tempdata使用服务器会话存储其内容的事实,这在多服务器环境中是有问题的。您可以实现自己的tempdata提供商,以使其使用cookie。一些可能的解决方案:
https://stackoverflow.com/a/28355862/1942895
https://brockallen.com/2012/06/11/cookie astem-tempdata-provider
http://vijayt.com/post/custom-tempdataprovider-for-azure