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:
- InProc
- StateServer
- 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:
Step 2: Add a controller “Home” as in the following screenshot:
Step 3: Add a view by right clicking on Index Method :
Step 4: Add the following code in your view:
- @{
- Layout = null;
- }
-
- <!DOCTYPEhtml>
- <html>
- <head>
- <metaname="viewport"content="width=device-width"/>
- <title>Index</title>
- </head>
- <body>
- <div>
- @ViewBag.Greeting is the current time....
- </div>
- </body>
- </html>
Step 5: Add the following code under index method of HomeController.
- public ActionResult Index()
- {
- ViewBag.Greeting = "Current Time is " + DateTime.Now;
- return View();
-
- }
Step 6: Run your application and you will find the following response.
In the next article, we will talk about TempData.