asp.net-mvc - asp.net mvc keep object alive, 信息

标签 asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我有这个代码

[HttpPost]
public ActionResult Index(LoginModel loginModel)
{
    if (ModelState.IsValid)
    { 
       // some lines of code . bla bla bla
       TempData["loginModel"] = loginModel;
       return RedirectToAction("index", "premium");
     }
     ...
}

还有这个 Controller

public ActionResult Index()
{
   var loginModel = TempData["loginModel"] as LoginModel;
   ...
}

现在,当页面加载时,一切似乎都正常。但是当我刷新时,一切都搞砸了,它说 loginModel 就像 null。问题是,我怎样才能跟踪当前的登录用户。我启用了表单例份验证。发送

错误如下


Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web     request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 


Line 22: 
Line 23:             var loginModel = TempData["loginModel"] as LoginModel;
Line 24:             string username = loginModel.username;
Line 25:             string password = loginModel.password;
Line 26:             premiumModel.username = username;

最佳答案

困惑

but when i refresh, everything messes up, it says that the loginModel is like null

回答

这是因为您已经读取了 TempData key ,一旦读取,该特定 key 的数据将会丢失。

var Value = TempData["keyName"] //Once read, data will be lost

问题

how can i like keep track of the current login users

回答

因此,即使在读取数据后仍要保留数据,您可以像下面这样将其激活

var Value = TempData["keyName"];
TempData.Keep();                 //Data will not be lost for all Keys
TempData.Keep("keyName");        //Data will not be lost for this Key

TempData 也适用于新的 Tabs/Windows,就像 Session 变量一样。

您也可以使用 Session 变量,唯一的主要问题是 Session 变量与 TempData 相比非常重。最后,您还可以跨 Controller /区域保存数据。

希望这篇文章能对您有所帮助。

关于asp.net-mvc - asp.net mvc keep object alive, 信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7592845/

相关文章:

c# - 当值为空时,Razor html 标签不会获取 ID

.net - Controller 中设置的模型属性未显示在 View 中

javascript - 仅当列表中添加了 ajax 请求时才调用 ajax 请求

c# - ASP.NET MVC 3 : DefaultModelBinder with inheritance/polymorphism

asp.net-mvc - 如何在 razor (CSHTML) 中设置内容类型?

c# - 使用编辑器模板在 MVC4 中提交后,回发对象未正确填充

asp.net-mvc - Visual Studio 2010 完整版和 ASP.NET MVC 2.0 模板

c# - 在不创建数据库的情况下将 Mini-Profilier 与 EF 4.3 和 MVC 4 结合使用

c# - MVC ajax 形式的嵌套对象在 Controller 中捕获

c# - 单元测试时我怎么能 "uninitialize"WebSecurity?