TempData在RedirectToAction期间不保留 [英] TempData not carrying over during RedirectToAction

查看:35
本文介绍了TempData在RedirectToAction期间不保留的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个有趣的问题,就是 TempData 对象没有将值传递给另一个控制器.

I have an interesting problem with the TempData object not passing values to another controller.

我在 Enroll Controller HttpPost 方法中将 TempData ["Enroll"] 设置为 Enroll 模型.然后,我在 Register Controller HttpGet 方法中读取了 TempData ["Enroll"] 对象,但该对象为 empty / null .

I set TempData["Enroll"] in the Enroll Controller's HttpPost method to an Enroll Model. I then read the TempData["Enroll"] object in the Register Controller's HttpGet method, but is empty/null.

我需要在3个控制器上保留所有这些数据.

I need to persist all of this data across 3 controllers.

有什么想法吗?

这是一个代码段

//EnrollController.cs
[HttpPost]
public ActionResult Index(EnrollModel model)
{
   // ...
   TempData["EnrollModel"] = model;
   return RedirectToAction("Index", "Register");
}

// RegisterController.cs
public ActionResult Index(string type)
{
    RegisterModel model = new RegisterModel();

    EnrollModel enrollModel = TempData["EnrollModel"] as EnrollModel;
    model.ClientType = enrollModel.ClientType;
    // ...
}

推荐答案

我之前遇到过TempData的这些限制.我充其量是不可靠和零星的.

I have come across these sorts of limitations with TempData before. I found it unrealiable and sporadic at best.

您需要考虑要实现的目标.如果您确实需要存储数据,那么实际上最好的存储位置是在db(或各种存储)中,这可能会显得有些矫kill过正,但这就是他们的目的.

You need to consider what you are trying to achieve. If you do need to store data, in practice the best place to do this is in a db (or store of sorts) it might seem a bit overkill but that is their purpose.

另外两点:

  1. 某些人可以直接访问RegisterController Index方法,而无需先执行其他操作,在这种情况下,您的代码将中断.

  1. Someone can hit your RegisterController Index method without going to the other before, in which case your code would break.

如果您正在执行多个向导样式的过程,为什么不将数据以其部分状态存储在db中,而仅在最后一个屏幕上完成该过程?这样,无论他们在哪里停止/启动或再次拾取它,您都将始终知道它们在过程中的位置.

If you are doing a multiple wizard style process, why not store the data in its partial state in the db, and complete the process only on the last screen? In this way no matter, where they stop/start or pick it up again, you will always know where they are in the process.

这篇关于TempData在RedirectToAction期间不保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆