Click here to Skip to main content
11,811,971 members (74,384 online)
Click here to Skip to main content

Learn MVC (Model view controller) Step by Step in 7 days – Day 4

, , 1 Aug 2014 CPOL 191.6K 205
Rate this:
Please Sign up or sign in to vote.
In day 4 we will look in to JSON ,Jquery ,Aysnch controllers and session management.
MVC 2 is quiet old and this article was written long years back. We would recommend you to start reading from our fresh Learn MVC 5 step by step series from here: -


So, what’s the agenda?.

In day 4 we will look in to JSON, Jquery ,Aysnch controllers and session management with MVC.

Get links of other parts of MVC article as below: -

Day 1: -Controllers, strong typed views and helper classes

Day 2: - Unit test, routing and outbound URLS

Day 3:- Partial views, Data annotations,Razor, Authentication and Authorization

Day 4:- JSON, JQuery, State management and Asynch controllers

Day 5:- Bundling , Minification , ViewModels,Areas and Exception handling

Day 6: - Display Modes,MVC OAuth,Model Binders,Layout and Custom view engine

Lab 15:- JSON , MVC and Jquery

In case you are new to JSON please read this before moving ahead with this lab ,What is JSON ?.

So in this lab we will expose a simple “Customer” object from MVC in JSON format and consume the same using Jquery.

For this lab please ensure that the project is created by using basic project template so that the necessary Jquery libraries are included with the MVC project.

Step 1 :- Create a simple Customer model

So the first step is to create a simple “Customer” class in the MVC project.

public class Customer
        private string _CustomerCode;
        public string CustomerCode
            get { return _CustomerCode; }
            set { _CustomerCode = value; }

Step 2 :- Expose Customer object as JSON

  • So, what’s the agenda?.

  • Day 1: -Controllers, strong typed views and helper classes

  • Day 2: - Unit test, routing and outbound URLS

  • Day 3:- Partial views, Data annotations,Razor, Authentication and Authorization

  • Day 4:- JSON, JQuery, State management and Asynch controller

  • Day 5:- Bundling , Minification , ViewModels,Areas and Exception handling

  • Day 6: - Display Modes,MVC OAuth,Model Binders,Layout and Custom view engine
  • Lab 15:- JSON , MVC and Jquery

  • Lab 16:- Session management in MVC (ViewData,ViewBag,TempData and session variables)

  • Lab 17:- Asynch controllers

  • What’s for Fifth day?

  • 50 MVC Interview questions with answers

  • Are you completely new to MVC?

  • To expose the customer object in JSON format we need to use “JsonResult” as shown in the below code snippet.
    public JsonResult getJson()
                Customer obj = new Customer();
                obj.CustomerCode = "c001";
                return Json(obj,JsonRequestBehavior.AllowGet);

    Please do once run the controller withthe above JSON action to check if the JSON result is displayed properly. If you are using chrome the display comes on the browser , if its internet explorer it spits out a file.

    Step 3 :- Consume the JSON controller in jquery

    In case you are new to Jquery , please read this What is jquery ?

    The next step is to consume the JSON data in Jquery using MVC view. So go ahead and add a view for example my view name is “LearnJquery.aspx”.

    First thing add the Jquery library at the top of the ASPX page. In case you do not find jquery library in your project that means you have not created the MVC project using the basic template.

    <script src="../../Scripts/jquery-1.8.2.js"></script>
    You can then make a call the controller which is exposing in JSON format using “getJson” method as shown below. Its takes three parameters:-
    • The first parameter in “getJson” is the MVC JSON URL with complete controller/action path format.
    • The second parameter is the data to be passed. For now its NULL as we are more interesting in getting JSON data rather posting data.
    • The last parameter is the call back method (“Display”) which will be invoked once we get the JSON data from the controller. The “Display” function is also available in the below code snippet. I am just putting an alert with the property name. FYI you can see how I have just typed “data.CustomerCode” , no parsing nothing the JSON data is automatically translated to javascript object.
     $.getJSON("/Json/getJson", null, Display);
    function Display(data)

    The complete MVC view HTML looks as shown below. I have created a simple HTML button and on the click event I am calling a “getJson” javascript method which makes a call to the JSON controller and displays the JSON data in a javascript alert.

    <script language="javascript">
            function getJson() {
                $.getJSON("/Json/getJson", null, Display);
                return true;
            function Display(data)
    <input type="button" value="See Json data" onclick="return getJson();"/>  

    This view I have invoked by using “DisplayJson” action.

    public class JsonController : Controller
            public ActionResult DisplayJson()
                return View("LearnJquery");

    Step 4 :- Run the application and see the data

    After you have done all the hardwork its time to hit the “DisplayJson” action to see the beauty running.

    Lab 16:- Session management in MVC (ViewData,ViewBag,TempData and session variables)

    The primary goal of MVC is to create web applications and web applications use HTTP protocol. Now HTTP protocol is a stateless by nature. So when you send a request to MVC application it serves the request and forgets about the request. Next time when the same user sends the request MVC treats that as a complete new request.

    Now think about the below situation:-

    • End user sends request to a MVC site.
    • MVC sends a login page.
    • User enters proper details and sends data to the MVC application.
    • MVC validates the user and sends home page of the site. MVC application now forgets everything about the user as it’s stateless.
    • Now user clicks on one of the home page links. This is sent to the MVC application and because MVC application has forgotten everything about the user, he sends a login page again for authentication….User would feel Weird…

    In short we need to have some kind of mechanism which will help us to remember states between request and response of MVC.

    There are 3 ways of maintaining states in MVC and these ways can be used depending from which layer to which layer you navigate.

    Temp data: -Helps to maintain data on redirects for a single request and response. Now the redirects can be from controller to controller or from controller to view.

    View data: - Helps to maintain data when you move from controller to view.

    View Bag: - It’s a dynamic wrapper around view data. When you use “Viewbag” type casting is not required. It uses the dynamic keyword internally.

    Session variables: - By using session variables we can maintain data until the browser closes.

    Let’s demonstrate the above fundamental with a demo.

    Step 1:- Create two controllers “DefaultController1” and “DefaultController2”.

    Add two controllers “DefaultController1” and “DefaultController2”.

    Step 2 :- Set Session , tempdata , viewdata and viewbag

    In the “Default1Controller” in “Action1” we set session,tempdata,viewdata and viewbag values as shown in the below code snippet. Once we set the values we do a redirect to the action “SomeOtherAction” which belongs to “Controller2”.

    public class Default1Controller : Controller
            // GET: /Default1/
            public ActionResult Action1()
                Session["Session1"] = "UntilBrowserCloses";
                TempData["FortheFullRequest"] = "FortheFullRequest";
                ViewData["Myval"] = "ControllertoView";
                ViewBag.MyVal = "ControllertoView";
                return RedirectToAction("SomeOtherAction","Default2");
            }    } 

    Step 3:- Read Session,tempdata ,viewdata and viewbag values

    In “Default2Controller” we will try to read values set in “Default1Controller”. Once the values are read we invoke a view called as “SomeView”.

    Please note I am setting “ViewData” and “ViewBag” before redirecting to the view.

    public class Default2Controller : Controller
            // GET: /Default2/
            public ActionResult SomeOtherAction()
               string str = Convert.ToString(TempData["FortheFullRequest"]);
               string str2 =  Session["Session1"].ToString();
               string str3 = Convert.ToString(ViewData["Myval"]);
               ViewData["Myval"] = "ControllertoView";
    ViewBag.MyVal = "ControllertoViewCollection";
                return View("SomeView");

    The “SomeView”view justdisplays the data present in “TempData” ,”ViewData” , “ViewBag” and “Session” .

    <%= TempData["FortheFullRequest"] %><br />
    <%= ViewData["Myval"] %><br />
    <%=  Session["Session1"] %>
    <%=  ViewBag.MyVal %>
    <a href="/Default1/Action1">Click</a> 

    So let’s put debug points in both the controller actions and let’s hit Default1 controller and Action1 action http://localhost:1203/Default1/Action1 . So in this action session,tempdata ,viewdata and viewbag are loaded. Below is how the watch window looks with data.

    Now from here we are redirecting to controller2 action “SomeOtherAction”.

    In controller2 you can see get “TempData” and “Session” variables but not “ViewBag” and “ViewData”( See “str3” and “str4” are set to null). In other words “ViewData” and “ViewBag” do not persist data in redirects while “TempData” and “Session” variables do.

    I have set “ViewData” and “ViewBag” with some data again before invoking the view “SomeView”.

    When the view gets invoked we can see all the data. In other words “ViewData” and “ViewBag” persist data from controller to view. And also tempdata and session have persisted data.

    Now when the view invokes I have kept a click hyper link which invokes “Action1” from “Controller1”. This is to simulate a fresh request.

    When we click on the link. All the other variables go off only session variables persist, see the below figure. It means “Session” variables can persist between requests.

    Below is a summary table which shows different mechanism of persistence.

    Maintains data between ViewData/ViewBag TempData ( For single request) Session
    Controller to Controller No Yes Yes
    Controller to View Yes Yes Yes
    View to Controller No No Yes

    Lab 17:- Asynch controllers

    MVC applications at the end of the day are web applications which are hosted inside IIS.Now when any request comes to MVC controller it pulls up a thread from thread pool and serves that request. In other words IIS web server maintains a pool of threads rather than creating threads from scratch again and again to gain performance benefits.
    Let’s assume that a web server has a thread pool size of 2. Now this is just an assumption because a pool size of two is very much hypothetical. But to make things simple consider that the thread pool size is 2.

    So let’s say first request comes to the site, IIS pulls up a readymade thread object from the thread pool and starts serving that request. In the meantime let’s say second request comes in so again IIS pulls up a thread from the thread pool and starts serving the second request.

    Now the fun starts when third request comes in. The IIS webserver does not have any more thread objects in the pool as those are already serving “request1” and “request2”. So he just moves the third request in to a waiting mode or the server can send “503 busy” message to the client.

    This situation is termed as “Thread Starvation”. Thread starvation situations can be overcome by making the request “Asynchronous”. So the request comes in and immediately the request is processed in an “Asynch” manner and releasing the thread serving the request immediately.

    So to avoid this we can achieve the same by making our controllers “Asynch”.

    Below is a nice video which demonstrates MVC Thread starvation.

    So let’s understand step by step how to implement MVC Asynch controllers.

    Step 1 :- Inherit from AsyncController class

    Consider the below controller class “HeavyController” which has an action “SomeHeavyMethod” and this action waits for 20 seconds. So let understand how we can make this simple controller aasynch controller.

    public class HeavyController : Controller
            // GET: /Heavy/
            public ActionResult SomeHeavyMethod()
                return View();

    So the first step is to inherit from “AsyncController” class.

    public class HeavyController : AsyncController

    Step 2 :- Mark methods with Async appended

    The next step is to append “Async” word after the methods. So you can see “SomeHeavyMethod” has been changed to “SomeHeavyMethodAsync”.

    The heavy logic code i.e. “Thread.Sleep” is moved to a different method and that method is invoked using task parallel library from the “SomeHeavyMethodAsync”.

    Every time a “Task” or a “Thread” is started we increment the outstanding operations counter by using “AsynchManager” and every time a multi-threaded task is completed we decrement the counter.

     public class HeavyController : AsyncController
    public void SomeHeavyMethodAsync()
    Task.Run(new Action(Heavy));
    public void Heavy()

    Step 3 :- Create the completed method

    Now once all the multi-threaded tasks complete and the outstanding operations are zero we need to return the view. So for the same we need to create an action result method with “Completed” word appended. This method gets called when all outstanding operations are zero.

    public ActionResult SomeHeavyMethodCompleted()
           return View();

    Step 4:- Ensure to create “SomeHeavyMethod.aspx” view

    Also ensure you add “SomeHeavyMethod” view with some text on it.

    <head runat="server">
    <meta name="viewport" content="width=device-width" />
    <title>Some heavy method</title>
            This is loaded after some time....

    Step 5 :- Run and enjoy

    Now try hitting “Heavy/SomeHeavyMethod” and see the output. I would suggest you to measure “Thread queued” to see the benefit of asynch controller. Watch this video to see how to measure “Thread Queued”

    What’s for Fifth day?

    Still working on it.

    Final note, you can watch my c# and MVC training videos on various sections like WCF, Silver light, LINQ, WPF, Design patterns, Entity framework etc. By any chance do not miss my .NET and c# interview questions and answers book from .

    For technical training related to various topics including ASP.NET, Design Patterns, WCF, MVC, BI, WPF contact or visit

    Start with MVC 5

    In case you want to start with MVC 5 start with the below video Learn MVC 5 in 2 days.

    50 MVC Interview questions with answers

    In case you are going for interviews you can read my 50 Important MVC interview questions with answer article

    Are you completely new to MVC?

    In case you are completely a fresher I will suggest to start with the below 4 videos which are 10 minutes approximately so that you can come to MVC quickly.

    Lab 1:- A simple Hello world ASP.NET MVC application.

    Lab 2:- In this Lab we will see how we can share data between controller and the view using view data.

    Lab 3 :- In this lab we will create a simple customer model, flourish the same with some data and display the same in a view.

    Lab 4 :- In this lab we will create a simple customer data entry screen with some validation on the view.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Authors

Shivprasad koirala
India India

I am an ex-Microsoft MVP for ASP/ASP.NET and currently a CEO of a small
E-learning company in India. We are very much active in making training videos, writing books and corporate trainings. Do visit my site for 
.NET, C#, Design Pattern, WCF, Silverlight, LINQ, ASP.NET, ADO.NET, SharePoint, UML, SQL Server  training 
and Interview questions and answers

Marla Sukesh
Instructor / Trainer Train IT
India India
Learning is fun but teaching is awesome.

Code re-usability is my passion ,Teaching and learning is my hobby, Becoming an successful entrepreneur is my goal.

By profession I am a Corporate Trainer.
I do trainings on WCF, MVC, Business Intelligence, Design Patterns, HTML 5, jQuery, JSON and many more Microsoft and non-Micrsoft technologiees.

Find my profile here

My sites


You may also be interested in...

Comments and Discussions

GeneralMy vote of 5 Pin
Sibeesh KV3-Oct-14 1:55
professionalSibeesh KV3-Oct-14 1:55 
QuestionA help needed Pin
Sibeesh KV3-Oct-14 0:58
professionalSibeesh KV3-Oct-14 0:58 
AnswerRe: A help needed Pin
CodeLocked28-Jan-15 5:49
memberCodeLocked28-Jan-15 5:49 
GeneralThanks Notes Pin
Akshay Bohra198830-Aug-14 8:29
memberAkshay Bohra198830-Aug-14 8:29 
GeneralRe: Thanks Notes Pin
Marla Sukesh6-Sep-14 8:11
professional Marla Sukesh6-Sep-14 8:11 
QuestionAsync Await Would Be Grate Pin
debdeep chaudhuri30-Jun-14 1:56
memberdebdeep chaudhuri30-Jun-14 1:56 
GeneralGreat Tutorial Pin
ram aguilar19-May-14 22:55
memberram aguilar19-May-14 22:55 
GeneralMy vote of 5 Pin
sandeepk.techie20-Feb-14 23:12
membersandeepk.techie20-Feb-14 23:12 
QuestionVery Nice article on MVC Pin
Member 1019928619-Feb-14 2:21
memberMember 1019928619-Feb-14 2:21 
QuestionHave query on TempData Pin
Murali Gowda13-Feb-14 19:41
professionalMurali Gowda13-Feb-14 19:41 
Questionissue Pin
Member 1059443713-Feb-14 4:41
memberMember 1059443713-Feb-14 4:41 
AnswerRe: issue Pin
Shivprasad koirala13-Feb-14 17:46
mvpShivprasad koirala13-Feb-14 17:46 
GeneralRe: issue Pin
Member 1059443713-Feb-14 18:40
memberMember 1059443713-Feb-14 18:40 
GeneralRe: Pin
Member 1059443713-Feb-14 18:40
memberMember 1059443713-Feb-14 18:40 
QuestionWhen will the rest be released? Pin
Member 1055288527-Jan-14 5:01
memberMember 1055288527-Jan-14 5:01 
AnswerRe: When will the rest be released? Pin
Shivprasad koirala13-Feb-14 17:47
mvpShivprasad koirala13-Feb-14 17:47 
QuestionNot getting basic template in visual studio 2010. Pin
Member 88024037-Jan-14 2:37
memberMember 88024037-Jan-14 2:37 
AnswerRe: Not getting basic template in visual studio 2010. Pin
Shivprasad koirala7-Jan-14 6:01
mvpShivprasad koirala7-Jan-14 6:01 
GeneralRe: Not getting basic template in visual studio 2010. Pin
Member 88024037-Jan-14 8:01
memberMember 88024037-Jan-14 8:01 
GeneralGreat Job - Looking forward to the rest of the series... Pin
jcoons29-Dec-13 2:57
memberjcoons29-Dec-13 2:57 
GeneralRe: Great Job - Looking forward to the rest of the series... Pin
Shivprasad koirala29-Dec-13 5:27
mvpShivprasad koirala29-Dec-13 5:27 
QuestionThanks for your excellent work sir Pin
Raju Mukherjee12-Dec-13 8:45
professionalRaju Mukherjee12-Dec-13 8:45 
Generalvery gud article Pin
Member 100167203-Dec-13 22:26
memberMember 100167203-Dec-13 22:26 
GeneralMy vote of 5 Pin
roscler26-Nov-13 18:37
professionalroscler26-Nov-13 18:37 
GeneralGood explaination with steps!... Pin
s.s.cheral20-Nov-13 18:30
members.s.cheral20-Nov-13 18:30 
GeneralMy 5 Pin
Shahriar Iqbal Chowdhury/Galib16-Nov-13 9:21
professionalShahriar Iqbal Chowdhury/Galib16-Nov-13 9:21 
GeneralMy vote of 5 Pin
Prasad Khandekar10-Nov-13 23:39
professionalPrasad Khandekar10-Nov-13 23:39 
GeneralRe: My vote of 5 Pin
Shivprasad koirala12-Nov-13 4:30
mvpShivprasad koirala12-Nov-13 4:30 
GeneralMy vote of 5 Pin
Steppenwolfe10-Nov-13 10:49
memberSteppenwolfe10-Nov-13 10:49 
GeneralRe: My vote of 5 Pin
Shivprasad koirala12-Nov-13 12:07
mvpShivprasad koirala12-Nov-13 12:07 
GeneralMy vote of 5 Pin
S. M. Ahasan Habib9-Nov-13 2:21
professionalS. M. Ahasan Habib9-Nov-13 2:21 
GeneralRe: My vote of 5 Pin
Shivprasad koirala12-Nov-13 12:07
mvpShivprasad koirala12-Nov-13 12:07 
QuestionMore Steps Pin
kiquenet.com7-Nov-13 22:28
memberkiquenet.com7-Nov-13 22:28 
GeneralMy vote of 5 Pin
Sunasara Imdadhusen20-Oct-13 18:57
memberSunasara Imdadhusen20-Oct-13 18:57 
GeneralMy vote of 5 Pin
M Rayhan19-Oct-13 23:23
memberM Rayhan19-Oct-13 23:23 
GeneralMy vote of 5 Pin
JasonMacD15-Oct-13 11:04
memberJasonMacD15-Oct-13 11:04 
Questiongood job Pin
tarekhaydar14-Oct-13 2:48
membertarekhaydar14-Oct-13 2:48 
QuestionKeep up the great work Pin
Rene Pilon13-Oct-13 7:01
memberRene Pilon13-Oct-13 7:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.151002.1 | Last Updated 2 Aug 2014
Article Copyright 2013 by Shivprasad koirala, Marla Sukesh
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid