且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在ASP MVC中使用和保留Session变量

更新时间:2023-12-03 23:23:28

您正在尝试在MVC上下文中使用Webforms心态,这根本无法工作...

很少需要像在Webforms中使用viewstate/session一样,在MVC中持久化"变量.在MVC中,通常是通过使用强类型视图并将模型的实例传递到视图中,从而从那里访问变量来完成的.

在极少数情况下,您可以使用TempData/ViewData/Session,但实际上不建议您使用它.

我建议您阅读有关MVC以及如何使用强类型视图的更多信息.此链接是一个好的开始.>

I'm working with an ASP MVC application and attempting to create a session variable in one controller and then later access that session variable in a different controller. I've found articles about this for PHP but I'm having trouble finding a solution for ASP MVC.

My code right now makes an ajax call to one controller to update an account number:

                $.ajax({
                    type: "PUT",
                    url: defender.techWebBaseUrl + "jobsinprogress/storenewmonitoringacctnumber/",
                    data: { acctNum: $("#newAcctNumber").val() }
                });

This executes on the controller:

  public void StoreNewMonitoringAcctNumber(string acctNum)
    {
        Session["MAN"] = acctNum;
    }

Which successfully creates the session variable. Later on in my workflow, in a completely separate/different controller I attempt to access this same variable:

.Configure(job, type, "sent", licenseStamp, EmployeeSignatureKey, Session["MAN"].ToString());

But every time that Session variable is NULL. I'm trying to understand how to persist Session variables in MVC because obviously the same rules from ASP.NET Web forms do not apply here. Also, these actions of saving the Session variable then attempting to access the Session variable must exist on different controllers so I absolutely must find a way to persist that variable.

Any advice is appreciated.

You are trying to use webforms mentality in a MVC context, which won't work at all...

Rarely do you need to "persist" variables in MVC the same way you would do in webforms by using viewstate/session. In MVC it's usually done by using a strongly typed view and pass an instance of the model into the view thus accessing the variable from there.

In some rare cases you can use TempData/ViewData/Session but it's really not recommended for what you are doing.

I recommend you read up more on MVC and how to use strongly-typed view. This link is a good start.