gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:21:52 25 4
gpt4 key购买 nike

我有这个代码

[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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com