Session In MVC 4 - Part 1

In the last article, I discussed what MVC is and Routing in MVC. Now let’s take it one step further and discuss how we manage sessions in MVC 4.

I hope readers are aware of session management techniques in ASP.NET.

What are sessions
The Web is stateless: That means every time a page gets loaded a new instance is used to create it. There are  many scenarios in which we need to save some values for further usage. Let'ss say I have counter variable and need to restore its value on each page load, so thar I can store it in sessions in order to use it again. Another example is username to show on page, etc.

Session Mode in ASP.NET:
  1. InProc
  2. StateServer
  3. SQLServer
Session State Mode State Provider
InProc In-memory object
StateServer Aspnet_state.exe
SQLServer Database

Session in MVC

In MVC the controller decides how to render view, meaning which values are accepted from View and which needs to be sent back in response. ASP.NET MVC Session state enables you to store and retrieve values for a user when the user navigatesto other view in an ASP.NET MVC application.

Let us take each task one by one, first we will take ViewBag:

ViewBag is a property of controllerBase. It’s nature is dynamic, that means we are able to add dynamic properties without compiling time errors. It allows us to share the value from controller to view.

Let’s work on the assignment by adding current date and time from controller to view using ViewBags .

Step 1: Select an Empty project of MVC 4 like the following:

 Select an Empty project

Step 2: Add a controller “Home” as in the following screenshot:

Add a controller

Step 3: Add a view by right clicking on Index Method :

Add view

Step 4: Add the following code in your view:

  1. @{  
  2.    Layout = null;  
  3. }  
  5. <!DOCTYPEhtml>  
  6.    <html>  
  7.       <head>  
  8.          <metaname="viewport"content="width=device-width"/>  
  9.          <title>Index</title>  
  10.       </head>  
  11.       <body>  
  12.          <div>  
  13.             @ViewBag.Greeting is the current time....  
  14.          </div>  
  15.       </body>  
  16. </html>  
Step 5: Add the following code under index method of HomeController.
  1. public ActionResult Index()  
  2. {  
  3.    ViewBag.Greeting = "Current Time is " + DateTime.Now;  
  4.    return View();  
  6. }  
Step 6: Run your application and you will find the following response.


In the next article, we will talk about TempData. 

Similar Articles