Reputation: 1897
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.
Upvotes: 1
Views: 3625
Reputation: 3280
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.
Upvotes: 3