Reputation: 815
I need to create something like a session variable in .net MVC. I'm using ViewData. First I set it in my Controller Index:
public ActionResult Index(int id)
{
ViewData["myID"] = id;
}
Then, I'll need to use it in another function of the same controller. However, I have to send it to my view. Store the data into a . Then read it again. View:
<input type="hidden" id="myID" name="myID" value='@ViewData["myID"]' />
Other function of the controller where I get the id:
[HttpPost, ValidateInput(false)]
public ActionResult Test(FormCollection form)
{
var pId = form["myID"];
}
It works, but looks wrong (I'm new in .net mvc). Is there a way where I can set this id one time in my controller and then read/get it when I need?
Thanks
Upvotes: 1
Views: 14346
Reputation: 1241
try this
for set
System.Web.HttpContext.Current.Session["Id"] = 1;
for get
var id=Convert.ToInt32(System.Web.HttpContext.Current.Session["Id"]);
Upvotes: 12