asp.net mvc 保持对象存活,信息 [英] asp.net mvc keep object alive, information

查看:18
本文介绍了asp.net mvc 保持对象存活,信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个代码

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

这里的控制器

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

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

now, when the page loads, everything seems to work fine. but when i refresh, everything messes up, it says that the loginModel is like null. the question is, how can i like keep track of the current login users. i have forms authentication enabled. tnx

错误如下

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;

推荐答案

困惑

但是当我刷新时,一切都搞砸了,它说 loginModel就像空

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

回答

这是因为您已经读取了 TempData 密钥,一旦读取,该特定密钥的数据将丢失.

This is due to the fact that you have read the TempData key and Once it is read, data will be lost for that particular key.

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

<小时>

问题

我如何跟踪当前登录用户

how can i like keep track of the current login users

回答

因此,即使在读取数据后仍要保留数据,您可以像下面一样活着

So to persist the data even after the data is read you can Alive it like below

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 变量一样.

TempData works in new Tabs/Windows also, like Session variable does.

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

You could use Session Variable also, Only major problem is that Session Variable are very heavy comparing with TempData. Finally you are able to keep the data across Controllers/Area also.

希望这篇文章能帮到你.

Hope this post will help you alot.

这篇关于asp.net mvc 保持对象存活,信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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