TempData丢失void func上的数据

时间:2018-05-17 14:36:00

标签: c# asp.net-mvc

我要做的是将List保存到TempData中,我稍后将其转换回其类型并传递给视图,但从控制器返回后的TempData会丢失其数据。

控制器A:

public ActionResult Index(int? Page, int? id, int? attId, int? EnrollNumber, int? attend, DateTime? reqDate, DateTime? reqDT, DateTime? reqTime, DateTime? StartDate, string deets = " ",  string preAppr = "", string type = "")
{

//some code

new UserInfoController().reLabelLogs(reqTime.Value.Date, reqTime.Value, id, 0, 0, null, attLogs);
var atLogs = new List<AttendanceLog>();
var temp = TempData["ppList"]; //its empty?
atLogs = (List<AttendanceLog>)TempData["ppList"];
return View(atLogs);
}   

Controller UserInfo:

public void reLabelLogs(DateTime? startDate, DateTime? startDateTime, int? empId, int? isPending, int? isManual, DateTime? manualDate
            , List<AttendanceLog> pList)
{

//some code
 if (pList == null)
            {
                  data = db.AttendanceLogs
                    .Where(z => z.EmpID == empId && z.Date >= startDate && z.Date <= today).ToList();
            }
            else
            {
                  noSave = true;
                  data = pList.ToList();
            }
foreach (var log in data)
 {
 // some code
 }
   TempData["ppList"] = data; //there is data but soon after the control goes back to Controller A it becomes null
}

我尝试了什么?

我尝试使用:

Session (but it would give NullException at UserInfoController)

ViewBag.ppList (same result as TempData)

Tried TempData.Keep(); and TempData.Peek();  (no help)

enter image description here

4 个答案:

答案 0 :(得分:1)

TempData和Session不起作用,因为您的UserInfoController没有上下文。您可以尝试将其传递给当前上下文:

var controller = new UserInfoController()
controller.Initialize(new RequestContext(this.HttpContext, this.RouteData));

controller.reLabelLogs(reqTime.Value.Date, reqTime.Value, id, 0, 0, null, attLogs);

或者您可以通过获取当前的http上下文来使用会话:

HttpContext.Current.Session["list"] = data;

答案 1 :(得分:0)

答案很简单:

  

TempData是一个会话支持的临时存储字典   可用于单个请求。在两者之间传递消息真是太棒了   控制器。

你必须使用不同的东西,比如Session。 我们需要知道你使用Session遇到了什么样的问题(如果我知道你已经尝试过这个解决方案)?

答案 2 :(得分:0)

Tempdata按照设计行事:在此处阅读更多内容 - Using Tempdata in ASP.NET MVC - Best practice

然而,会话可以工作,所以也许你做错了什么

答案 3 :(得分:0)

要访问辅助控制器中的application.js变量,您应该使用

session