Monday, December 30, 2013

Handling Session values in MVC

When using MVC, there are occasions where I need to move data between the two prime layers - the View and Controller. It is at times like this that Session Variables come in handy.

Though MVC already provides two options for data  mobility namely ViewData and ViewBag, they did not help my need to sustain values for every jQuery/ajax call from UI change event to controller methods, as I need to be constantly stringing up those control values(drop downs) together for the final submit process. To overcome this issue, I decided to use Session values to preserve transported data from my View.

Here I am using Session variables and also to demonstrate how to store/retrieve the variable...

public class HomeController : Controller

  public JsonResult GetDataList()
   // Code goes here...

  Session["username"] = "test user";


In the View, retrieving this value is also straight forward.
If you are using Razor, plus this in to your View:

In your view (SampleView.cshtml in this case), you could use it as given below to test or display the value.
@if(@(Session["uservalue"] != null)
 <span id='span1'>
  <h3>Welcome user, <b>@(Session["uservalue"]</b> !!!</h3>