tempdata的使用

tempdata是用于传输一些临时的数据,例如在各个控制器Action间传递临时的数据或者给View传递一些临时的数据,相信大家都看过“在ASP.NET页面间传值的方法有哪几种”这个面试题,在ASP.NET MVC中TempData的就是其中的一种传值方法。TempData默认是使用Session来存储临时数据的,TempData中存放的数据只一次访问中有效,一次访问完后就会删除了的。这个一次访问指的是一个请求到下一个请求,因为在下一个请求到来之后,会从Session中取出保存在里面的TempData数据并赋值给TempData,然后将数据从Session中删除。在mvc2中的SessionStateTempDataProvider.cs代码中我们可以看出来:

  public virtual IDictionary<string, object> LoadTempData(ControllerContext controllerContext) {
            HttpSessionStateBase session = controllerContext.HttpContext.Session;

            if (session != null) {
                Dictionary<string, object> tempDataDictionary = session[TempDataSessionStateKey] as Dictionary<string, object>;

                if (tempDataDictionary != null) {
                    // If we got it from Session, remove it so that no other request gets it
                    session.Remove(TempDataSessionStateKey);
                    return tempDataDictionary;
                }
            }

            return new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase);
        }

原文地址:https://www.cnblogs.com/linjiancun/p/1830777.html