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.
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>
- public ActionResult Index()
- {
- ViewBag.Greeting = "Current Time is " + DateTime.Now;
- return View();
- }

In the next article, we will talk about TempData.

Venugopal ReddyPosted Nov 5, 2020, 11:54 PM
Hi Sir when
Dharmendra Kumar PanditPosted Feb 15, 2020, 9:23 PM
Very nice....
kamal kumarPosted Aug 29, 2019, 2:03 AM
Sir where is left 3 parts
Nishant MittalPosted Jan 20, 2016, 1:13 AM
Thanks Jaco....
Jaco ZwartsPosted Jan 20, 2016, 12:58 AM
Nishant, really good tutorial thanks
Santhakumar MunuswamyPosted Jan 13, 2016, 10:20 AM
Thanks for nice share
Nishant MittalPosted Jan 11, 2016, 10:18 AM
Thanks and all the too ??
Manoj KallaPosted Jan 11, 2016, 9:32 AM
Very good article, Now days I also started on writing MVC.