Sending Complex JSON Objects To ASP.NET MVC View Using JQuery Ajax

Today while working in an ASP.NET MVC project I faced a certain scenario where I need to bind the complex object returned from the controller to the View. So in the beginning I was facing problem to achieve the same then with some research I was able to achieve the same. So today I am going to teach how to bind the JSON result object to the DropDownlistFor Control in ASP.NET MVC.

Before going ahead and talking about complex object let’s talk about ViewModel.

ViewModel - In MVC we are known of the terminology like View, Controller and Model. In MVC we have another Model that is a layer between View and Model which provide us separation of concern between View and Model. We can also say that View Model contains the data which we want to show into the View section. View Model allows us to shape multiple entities of a class into a single model class object and we can inject also View logic in View Model.


Figure 1.0: View Model demonstrating ViewModel as a collection of class objects that are needed to be displayed in View.

Let’s get practical switch to Visual studio and follow these steps:
  1. Start Visual Studio.
  2. Select File, New, then New Project.
  3. Select Visual C# and in menu of C# select Web section.
  4. Select ASP.NET Web application and select ASP.NET MVC.
  5. Name your project and now follow the screenshots.

Step 6: Add Controller and Name your controller name as shown below:

Web Application
Figure 2.0: Creating MVC Web Application

Creating MVC Web Application
Figure 3.0: Creating MVC Web Application Controller Name

Step 7: Adding your Model class.

E.g.: Employee, Meeting as shown below,

Meeting Class

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace ComplexObjectViewModel.Models  
  6. {  
  7.     //class contains Meeting Details with ID and Name  
  8.     public class Meeting  
  9.     {  
  10.         public int MeetingId  
  11.         {  
  12.             get;  
  13.             set;  
  14.         }  
  15.         public string MeetingName  
  16.         {  
  17.             get;  
  18.             set;  
  19.         }  
  20.     }  
  21. }  
Employee Model
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace ComplexObjectViewModel.Models  
  6. {  
  7.     public class Employee  
  8.     {  
  9.         public int EmployeeId  
  10.         {  
  11.             get;  
  12.             set;  
  13.         }  
  14.         public string EmployeeName  
  15.         {  
  16.             get;  
  17.             set;  
  18.         }  
  19.     }  
  20. }  
Step 8: Now we will create View Model which will contain properties of type model which can be used in View.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using ComplexObjectViewModel.Models;  
  6. namespace ComplexObjectViewModel.Models  
  7. {  
  8.     public class MeetingVM  
  9.     {  
  10.         public Meeting objMeeting  
  11.         {  
  12.             get;  
  13.             set;  
  14.         } //contains single meeting details  
  15.         public List < Meeting > objMeetinglst  
  16.             {  
  17.                 get;  
  18.                 set;  
  19.             } //contains the List of Meetings  
  20.         public Employee objEmploye  
  21.         {  
  22.             get;  
  23.             set;  
  24.         } //contains single employee details  
  25.         public List < Employee > objEmployeelist  
  26.             {  
  27.                 get;  
  28.                 set;  
  29.             } //contains list of Employees  
  30.         public string isSelectedMeetng  
  31.         {  
  32.             get;  
  33.             set;  
  34.         } //Binding the Selected value of Meeting  
  35.         public string isSelectedEmployee  
  36.         {  
  37.             get;  
  38.             set;  
  39.         } //Binding the Selected value of Employee  
  40.     }  
  41. }  
Now we will create our view which is strongly typed view of MeetingVM that will contain list of Employees and Meeting as shown below. Here I am creating two dropdown list which will populate the list of Meeting and list of Employees as shown below:

View
  1. @model ComplexObjectViewModel.Models.MeetingVM  
  2.      @*STRONGLY TYPED MODEL OF MeetingVM contains definition for List of Meetings, List of //Participants*@  
  3.   
  4. @{  
  5.     Layout = null;  
  6. }  
  7.   
  8. <!DOCTYPE html>  
  9.   
  10. <html>  
  11. <head>  
  12.     <meta name="viewport" content="width=device-width" />  
  13.     <title>Index</title>  
  14. </head>  
  15. <body>  
  16.     @using (Html.BeginForm())   
  17.     {  
  18.          
  19.     <table>  
  20.         <tr>  
  21.             <td>  
  22.                 Meeting Details  
  23.   
  24.             </td>  
  25.             <td>  
  26.                 @*contains list of Meetings*@  
  27.                 @Html.DropDownListFor(M => M.isSelectedMeetng, new SelectList(Model.objMeetingList, "MeetingId""MeetingName"), "---Select---")  
  28.   
  29.             </td>  
  30.   
  31.         </tr>  
  32.         <tr>  
  33.             <td>  
  34.                 Employee Details  
  35.   
  36.             </td>  
  37.   
  38.             <td>  
  39.                 @*contains list of Employees*@  
  40.                 @Html.DropDownListFor(M => M.isSelectedEmployee, new SelectList(Model.objEmployeeList, "EmployeeId""EmployeeName"), "---Select---")  
  41.   
  42.             </td>  
  43.   
  44.         </tr>  
  45.   
  46.     </table>  
  47.               
  48.     }  
  49.       
  50. </body>  
  51. </html>  
In controller I have added hardcoded list of Employees and Meeting in real time project this will come from DB.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using ComplexObjectViewModel.Models;  
  7. namespace ComplexObjectViewModel.Controllers  
  8. {  
  9.     public class MeetingController: Controller  
  10.     {  
  11.         //  
  12.         // GET: /Meeting/  
  13.         public ActionResult Index()  
  14.         {  
  15.             MeetingVM obj = new MeetingVM();  
  16.             obj.objEmploye = new Employee();  
  17.             obj.objEmployeeList = new List < Employee > ();  
  18.             obj.objMeetingList = new List < Meeting > ();  
  19.             obj.objEmploye.EmployeeId = 1;  
  20.             obj.objEmploye.EmployeeName = "saillesh";  
  21.             obj.objEmployeeList.Add(obj.objEmploye);  
  22.             obj.objEmploye = new Employee();  
  23.             obj.objEmploye.EmployeeId = 2;  
  24.             obj.objEmploye.EmployeeName = "Nishant";  
  25.             obj.objEmployeeList.Add(obj.objEmploye);  
  26.             obj.objEmploye = new Employee();  
  27.             obj.objEmploye.EmployeeId = 3;  
  28.             obj.objEmploye.EmployeeName = "Ankit";  
  29.             obj.objEmployeeList.Add(obj.objEmploye);  
  30.             obj.objMeeting = new Meeting();  
  31.             obj.objMeeting.MeetingId = 1;  
  32.             obj.objMeeting.MeetingName = "Retails";  
  33.             obj.objMeetingList.Add(obj.objMeeting);  
  34.             obj.objMeeting = new Meeting();  
  35.             obj.objMeeting.MeetingId = 2;  
  36.             obj.objMeeting.MeetingName = "Operational";  
  37.             obj.objMeetingList.Add(obj.objMeeting);  
  38.             obj.objMeeting = new Meeting();  
  39.             obj.objMeeting.MeetingId = 3;  
  40.             obj.objMeeting.MeetingName = "Audit";  
  41.             obj.objMeetingList.Add(obj.objMeeting);  
  42.             return View(obj); //returning ViewModel object to the View  
  43.         }  
  44.     }  
  45. }  
Run the application you will see the output as shown below:

Select detail
Figure 4.0: Sample 1

Sample
Figure 5.0: Sample 2

So here we can see how we can shape multiple entities of a class into a single model class with the help of View Model class.

Now we will focus to our problem or objective i.e. that on dropdown change of Participant(Employee) I will make a Ajax GET call to the controller and return complex object of View model and return the Json object and bind the data to the new Html.dropdownlist. For example, Occupation for that we will create a new model class called Occupation as in the following,
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace ComplexObjectViewModel.Models  
  7. {  
  8.    public class Occupation  
  9.    {  
  10.   
  11.       public int OccupationId { getset; }  
  12.       public string OccupationName { getset; }  
  13.    }  
  14. }  
Adding the model to the ViewModel to be used in the View as shown below:

Add the following properties in ViewModel Class.
  1. public Occupation objOccupation { getset; }//contain Single occupation class properties  
  2.   
  3. public List<Occupation> objOccupationList { getset; }//contains the list of occupation class properties  
Now on the page load pass the null object of OccupationList to the view.

The page will appear as shown below:

Page View
Figure 6.0: Page View

Now on Employee Details dropdown change  I will load the Detail of the Employee Occupation based on the selected Employee Value as shown below using Ajax. I hope you are familiar to Ajax, if not I would request you to learn Ajax before moving ahead of the article.

So now will add our Ajax Call for calling a GET method from Controller:
  1. <script>  
  2. $(document).ready(function ()  
  3. {  
  4.     $("#isSelectedEmployee").change(function ()  
  5.     {  
  6.         {  
  7.             var Value = $("#isSelectedEmployee option:selected").val();  
  8.             $.ajax(  
  9.             {  
  10.                 url: '/Meeting/FillOccupation',  
  11.                 data:  
  12.                 {  
  13.                     'id': Value  
  14.                 },  
  15.                 dataType: "json",  
  16.                 type: "GET",  
  17.                 error: function ()  
  18.                 {  
  19.                     alert(" An error occurred.");  
  20.                 },  
  21.                 success: function (data)  
  22.                 {  
  23.                     debugger;  
  24.                     for (var key in data)  
  25.                     {  
  26.                         if (data[key].OccupationId)  
  27.                         {  
  28.                             var optionhtml = '<option value="' + data[key].OccupationId + '">' + data[key].OccupationName + '</option>';  
  29.                             $("#isSelectedOccupation").append(optionhtml);  
  30.                         }  
  31.                     }  
  32.                 }  
  33.             })  
  34.         }  
  35.     });  
  36. })  
  37. </script>  
FillOccupation method in Controller which will receive the Id from the Ajax call and same id will search in the list of Occupation and the list of Occupation object is returned in JSON format and same is bind to my Occupation DropdownListfor.

Note: I have hardcoded the occupation list and same will be displayed from the DB.
  1. public ActionResult FillOccupation(int ? Id)  
  2. {  
  3.     MeetingVM obj = new MeetingVM();  
  4.     obj.objEmploye = new Employee();  
  5.     obj.objEmployeeList = new List < Employee > ();  
  6.     obj.objMeetingList = new List < Meeting > ();  
  7.     obj.objEmploye.EmployeeId = 1;  
  8.     obj.objEmploye.EmployeeName = "saillesh";  
  9.     obj.objEmployeeList.Add(obj.objEmploye);  
  10.     obj.objEmploye = new Employee();  
  11.     obj.objEmploye.EmployeeId = 2;  
  12.     obj.objEmploye.EmployeeName = "Nishant";  
  13.     obj.objEmployeeList.Add(obj.objEmploye);  
  14.     obj.objEmploye = new Employee();  
  15.     obj.objEmploye.EmployeeId = 3;  
  16.     obj.objEmploye.EmployeeName = "Ankit";  
  17.     obj.objEmployeeList.Add(obj.objEmploye);  
  18.     obj.objMeeting = new Meeting();  
  19.     obj.objMeeting.MeetingId = 1;  
  20.     obj.objMeeting.MeetingName = "Retails";  
  21.     obj.objMeetingList.Add(obj.objMeeting);  
  22.     obj.objMeeting = new Meeting();  
  23.     obj.objMeeting.MeetingId = 2;  
  24.     obj.objMeeting.MeetingName = "Operational";  
  25.     obj.objMeetingList.Add(obj.objMeeting);  
  26.     obj.objMeeting = new Meeting();  
  27.     obj.objMeeting.MeetingId = 3;  
  28.     obj.objMeeting.MeetingName = "Audit";  
  29.     obj.objMeetingList.Add(obj.objMeeting);  
  30.     obj.objOccupationList = new List < Occupation > ();  
  31.     obj.objOccupation = new Occupation();  
  32.     obj.objOccupation.OccupationId = 2;  
  33.     obj.objOccupation.OccupationName = "INDIAN NAVY";  
  34.     obj.objOccupationList.Add(obj.objOccupation);  
  35.     obj.objOccupation = new Occupation();  
  36.     obj.objOccupation.OccupationId = 1;  
  37.     obj.objOccupation.OccupationName = "Software Engineer";  
  38.     obj.objOccupationList.Add(obj.objOccupation);  
  39.     obj.objOccupation = new Occupation();  
  40.     obj.objOccupation.OccupationId = 1;  
  41.     obj.objOccupation.OccupationName = "Author";  
  42.     obj.objOccupationList.Add(obj.objOccupation);  
  43.     obj.objOccupation = new Occupation();  
  44.     obj.objOccupation.OccupationId = 3;  
  45.     obj.objOccupation.OccupationName = "Business";  
  46.     obj.objOccupationList.Add(obj.objOccupation);  
  47.     //collecting the list of Occupation who has Occupation id same as EmployeeId  
  48.     var ListOfOcuupation = obj.objOccupationList.Where(m => m.OccupationId == Id).ToList();  
  49.     obj.objOccupationList = new List < Occupation > ();  
  50.     foreach(Occupation objOcupation in ListOfOcuupation)  
  51.     {  
  52.         obj.objOccupationList.Add(objOcupation);  
  53.     }  
  54.     return Json(obj.objOccupationList, JsonRequestBehavior.AllowGet);  
  55. }  
Now I have put debugger in the JQuery function to check the flow as shown below:

As soon as User selects the Employee Details Dropdown list the javascript function is called as shown below:

Picture Demonstrating Ajax
Figure 7.0 : Picture Demonstrating Ajax Call to FillOccupation method

The value of selected Dropdown list is stored in Value var and same is passed to the controller as shown below:

Get method
Figure 8.0 : Get method hits to FillOccupation method

Now the list of Occupation is searched where Occupation Id is same as Employee Id and same list is returned in JSON format as shown below.

JSON object
Figure 9.0: JSON object is returned to JavaScript function

Now same data is collected in object in JavaScript as shown below:

Received data in Object
Figure 10.0: Received data in Object

Looping threw the received objects
Figure 11.0: Looping throw the received objects using key eg 0,1 refereeing to object array value and looping to the object property as shown.

Appending the list
Figure 12.0: Appending the list to Occupation Dropdownlist

Received JSON data
Figure 13.0: Received JSON data appended to the Dropdown of Employee Occupation.

Conclusion

In this article we specially focused about View Model and how to send complex JSON objects to ASP.NET MVC View. Your comments, votes and suggestions motivate us for writing more stuff like this.

 


Similar Articles