Retrieve a Session Object in a View in MVC

When we are working on our project, several situations and challenges may come. We need to face all these situations, sometime small problems may take 1 to 2 hours. After spending this much of precious time we think this could have been implemented in 5 minutes, but why we spent 1 to 2 hours?

So today  I am explaining a simple problem which could help you to save time while coding. This is a small and simple problem.

Could we use a session object in our view?

Answer- The answer is yes.

Let me explain how, I can use it and retrieve it in my view.

This is my HomeController and I have the following method, where I have saved my name in a session variable.

  1. public ActionResult Employee()  
  2. {  
  3.    Session["username"] = "debendra Prasad Dash";  
  4.    return View();  
  5. }  
Now, retrieve this variable in any view.

So this is very simple.

Go to the view where you want to retrieve the value of session. Add a Hidden field there like this:
  1. <input type="hidden" value="@Session["username"]" id="myHiddenVar" />  
Here the value will be my session value.

Write a simple jQuery to display the value on any button click or anything like this:
  1. var x = $('#myHiddenVar').val();  
  2. $('#displayname').val(x.toString());  
So this is the simple way to retrieve a session object in a view.