1

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

user6824563
  • 735
  • 6
  • 25
  • 47

1 Answers1

12

try this

for set

System.Web.HttpContext.Current.Session["Id"] = 1;

for get

var id=Convert.ToInt32(System.Web.HttpContext.Current.Session["Id"]);
ali zarei
  • 1,212
  • 11
  • 17
  • Perfect. Thanks! Just a question... Does this session expire after a period of time? – user6824563 Dec 06 '17 at 23:34
  • yes it expiered after period . see this links [How to set session timeout in web.config](https://stackoverflow.com/questions/1205828/how-to-set-session-timeout-in-web-config) – ali zarei Dec 06 '17 at 23:42