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

3
  • 3
    ViewData!=Session Commented Dec 6, 2017 at 22:49
  • 5
    Why not just use Session? It works just find in MVC. Otherwise, what you're doing is just fine - use ViewData to send the data to the view, and a form control to send it back to the controller. Commented Dec 6, 2017 at 22:51
  • I couldn't find anything about session in MVC Commented Dec 6, 2017 at 23:03

1 Answer 1

12

try this

for set

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

for get

var id=Convert.ToInt32(System.Web.HttpContext.Current.Session["Id"]);
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. Thanks! Just a question... Does this session expire after a period of time?
yes it expiered after period . see this links How to set session timeout in web.config

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.