ASP.NET MVC5 - Passing ViewModel Using JQuery Ajax And Strongly Typed View

Introduction
 
In this article, I will demonstrate how to work with ViewModel in ASP.NET MVC5 Using jQuery Ajax and Strongly Typed View. After going through this article, you will get the benefits of ViewModel features. Okay! Let's move forward.
 
Prerequisites 
  • Visual Studio
  • Basic knowledge of ASP.NET MVC
  • Basic knowledge of jQuery
  • Basic knowledge of CSS
Article Flow
  • Create an ASP.NET MVC Empty project
  • What is View Model
  • Create a View Model
  • Add the dummy values to ViewModel
  • Create the Strongly Typed View
  • Pass ViewModel From jQuery Ajax
Create an ASP.NET MVC Empty project 
  • To create ASP.NET MVC empty project, follow the below steps one by one. Here, I have used Visual Studio 2013.
  • Select New Project -> Visual C# -> Web -> ASP.NET Web Application and enter your application name. Here, I named it as "ViewModelUsingjQueryAjax".
  • Now, click OK.
  • Then, select Empty MVC template and click OK to create the project.
  • Once you click OK, the project will be created with the basic architecture of MVC.
  • If you are not aware of how to create an Empty ASP.NET Web Application, please visit Step 1 and Step 2 to learn. Once you complete these steps, you will get the screen as below.
 
What is View Model 
 
ViewModels allow you to shape multiple entities from one or more data models or sources into a single object, optimized for consumption and rendered by the view. With the help of ViewModels, we can work with multiple models in a time.
 
Create a View Model
 
To create a View Model we must have more than a model or entity in our project. So, now let's create the model first. In the below, you can see that I have created two models with the name of Employee and Contact.
  1. public class Employee {  
  2.     public int EmpID {  
  3.         get;  
  4.         set;  
  5.     }  
  6.     public string Name {  
  7.         get;  
  8.         set;  
  9.     }  
  10.     public string Designation {  
  11.         get;  
  12.         set;  
  13.     }  
  14. }  
  15. public class Contact {  
  16.     public int EmpID {  
  17.         get;  
  18.         set;  
  19.     }  
  20.     public string Email {  
  21.         get;  
  22.         set;  
  23.     }  
  24.     public string MobileNo {  
  25.         get;  
  26.         set;  
  27.     }  
  28.     public string Address {  
  29.         get;  
  30.         set;  
  31.     }  
These are the normal model or entity. Now let's create a ViewModel. In the below code you can see that I have created aEmployeeContact_ViewModel. While creating a ViewModel, we have to mention which model or entity should exist in ViewModel.
  1. public class EmployeeContact_ViewModel  
  2. {  
  3.    public Employee employeeDetails { get; set; }  
  4.    public Contact contactDetails { get; set; }  
  5. }  
Add the dummy values to ViewModel
  
Before Adding dummy values to it, let's create the controller and action.
 
Create a Controller and View
 
Now, create an empty Controller and View. Here, I created a Controller with the name of "DemoController". Whenever we create an empty Controller, it is created with an empty Index action method. And I have created a LoadEmployees Action.
  1. Employee emp = new Employee();  
  2. emp.EmpID = 1;  
  3. emp.Name = "Gnanavel Sekar";  
  4. emp.Designation = "Sr.Software Engineer";  
  5. Contact contact = new Contact();  
  6. contact.EmpID = 1;  
  7. contact.Address = "test";  
  8. contact.Email = "[email protected]";  
  9. contact.MobileNo = "9876543210";  
  10. EmployeeContact_ViewModel viewModel = new EmployeeContact_ViewModel()  
  11. {  
  12.    contactDetails = contact,  
  13.    employeeDetails = emp  
  14. };  
Create the Strongly Typed View
 
To know about Strongly Typed View refer here. Likewise, I have created a strongly typed view below.
  1. @model ViewModelUsingJqueryAjax.Models.EmployeeContact_ViewModel  
  2. @ {  
  3.     ViewBag.Title = "LoadEmployees";  
  4. }  
  5. @using(Html.BeginForm()) {  
  6.     @Html.AntiForgeryToken() < div class = "form-horizontal" > < h4 > Employee < /h4> < hr / > @Html.ValidationSummary(true""new {  
  7.         @class = "text-danger"  
  8.     }) < div class = "form-group" > @Html.LabelFor(model => model.employeeDetails.EmpID, htmlAttributes: new {  
  9.         @class = "control-label col-md-2"  
  10.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.employeeDetails.EmpID, new {  
  11.         htmlAttributes = new {  
  12.             @class = "form-control"  
  13.         }  
  14.     })  
  15.     @Html.ValidationMessageFor(model => model.employeeDetails.EmpID, ""new {  
  16.         @class = "text-danger"  
  17.     }) < /div> < /div> < div class = "form-group" > @Html.LabelFor(model => model.employeeDetails.Name, htmlAttributes: new {  
  18.         @class = "control-label col-md-2"  
  19.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.employeeDetails.Name, new {  
  20.         htmlAttributes = new {  
  21.             @class = "form-control"  
  22.         }  
  23.     })  
  24.     @Html.ValidationMessageFor(model => model.employeeDetails.Name, ""new {  
  25.         @class = "text-danger"  
  26.     }) < /div> < /div> < div class = "form-group" > @Html.LabelFor(model => model.employeeDetails.Designation, htmlAttributes: new {  
  27.         @class = "control-label col-md-2"  
  28.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.employeeDetails.Designation, new {  
  29.         htmlAttributes = new {  
  30.             @class = "form-control"  
  31.         }  
  32.     })  
  33.     @Html.ValidationMessageFor(model => model.employeeDetails.Designation, ""new {  
  34.         @class = "text-danger"  
  35.     }) < /div> < /div> < h4 > Contact < /h4> < hr / > @Html.ValidationSummary(true""new {  
  36.         @class = "text-danger"  
  37.     }) < div class = "form-group" > @Html.LabelFor(model => model.contactDetails.MobileNo, htmlAttributes: new {  
  38.         @class = "control-label col-md-2"  
  39.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.contactDetails.MobileNo, new {  
  40.         htmlAttributes = new {  
  41.             @class = "form-control"  
  42.         }  
  43.     })  
  44.     @Html.ValidationMessageFor(model => model.contactDetails.MobileNo, ""new {  
  45.         @class = "text-danger"  
  46.     }) < /div> < /div> < div class = "form-group" > @Html.LabelFor(model => model.contactDetails.Address, htmlAttributes: new {  
  47.         @class = "control-label col-md-2"  
  48.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.contactDetails.Address, new {  
  49.         htmlAttributes = new {  
  50.             @class = "form-control"  
  51.         }  
  52.     })  
  53.     @Html.ValidationMessageFor(model => model.contactDetails.Address, ""new {  
  54.         @class = "text-danger"  
  55.     }) < /div> < /div> < div class = "form-group" > @Html.LabelFor(model => model.contactDetails.Email, htmlAttributes: new {  
  56.         @class = "control-label col-md-2"  
  57.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.contactDetails.Email, new {  
  58.         htmlAttributes = new {  
  59.             @class = "form-control"  
  60.         }  
  61.     })  
  62.     @Html.ValidationMessageFor(model => model.contactDetails.Email, ""new {  
  63.         @class = "text-danger"  
  64.     }) < /div> < /div> < div class = "form-group" > < div class = "col-md-offset-2 col-md-10" > < input type = "submit"  
  65.     id = "btnViewModel"  
  66.     value = "Create"  
  67.     class = "btn btn-default" / > < /div> < /div> < /div>  
  68. } < div > @Html.ActionLink("Back to List""Index") < /div>  
You can see that I have created the button with a type of submitting. So, here we can directly pass our view data to the controller using a strongly typed view.
  1. <input type="submit" id="btnViewModel" value="Create" class="btn btn-default" />  
And create a post action in a controller.
  1. [HttpPost]  
  2. public ActionResult LoadEmployees(EmployeeContact_ViewModel viewModel)  
  3. {  
  4.    return View();  
  5. }  
Now, run your application.
  
 
We returned the static data to View Model and the ViewModel is bound to each control by using a strongly typed view. Here we can get the view data in the controller using a strongly typed view. In some cases, we will go with the Client side. In that case, we have to know how to pass the ViewModel from jQuery to Ajax right?. Now let's see that
 
 Pass ViewModel From jQuery Ajax
 
First, we will change the button type because we need to call our jQuery function right? Otherwise, it automatically calls the post action while we have the strongly typed view. So, I have changed the type="submit" to type="button" as below.
  1. <input type="button" id="btnViewModel" value="Create" class="btn btn-default" />   
Now let's write the logic to fetch the value from our view controller. We can get nested class properties id in jQuery, using “@Html.IdFor()”. In the following way, we can read nested class properties value. Or we can define the id for our control and get the value by directly mentioning the control id. 
  1. $('#@Html.IdFor(m=>m.employeeDetails.EmpID)').val();  
In the below code, we have created two objects with the name of employeeDetails, contactDetails and we assigned the value to it. Each and every model object should match here otherwise we will not get the data in our controller.
  1. <script type="text/javascript">  
  2.     $(document).ready(function() {  
  3.         $("#btnViewModel").click(function() {  
  4.             var employeeDetails = {  
  5.                 EmpID: $('#@Html.IdFor(m=>m.employeeDetails.EmpID)').val(),  
  6.                 Name: $('#@Html.IdFor(m=>m.employeeDetails.Name)').val(),  
  7.                 Designation: $('#@Html.IdFor(m=>m.employeeDetails.Designation)').val()  
  8.             }  
  9.             var contactDetails = {  
  10.                 MobileNo: $('#@Html.IdFor(m=>m.contactDetails.MobileNo)').val(),  
  11.                 Address: $('#@Html.IdFor(m=>m.contactDetails.Address)').val(),  
  12.                 Email: $('#@Html.IdFor(m=>m.contactDetails.Email)').val(),  
  13.                 EmpID: $('#@Html.IdFor(m=>m.employeeDetails.EmpID)').val(),  
  14.             }  
  15.             var viewModel = {  
  16.                 "employeeDetails": employeeDetails,  
  17.                 "contactDetails": contactDetails  
  18.             }  
  19.             $.ajax({  
  20.                 type: "post",  
  21.                 url: "/Demo/LoadEmployees",  
  22.                 data: viewModel,  
  23.                 datatype: "json",  
  24.                 cache: false,  
  25.                 success: function(data) {  
  26.                     alert("View Model Passed Successfully");  
  27.                 },  
  28.                 error: function(xhr) {  
  29.                     alert('No Valid Data');  
  30.                 }  
  31.             });  
  32.         });  
  33.     });  
  34. </script>  
Now, run your application, After clicking create a button,
 
Complete Controller 
  1. using System.Web.Mvc;  
  2. using ViewModelUsingjQueryAjax.Models;  
  3. namespace ViewModelUsingjQueryAjax.Controllers {  
  4.     public class DemoController: Controller {  
  5.         // GET: Demo  
  6.         public ActionResult Index() {  
  7.             return View();  
  8.         }  
  9.         public ActionResult LoadEmployees() {  
  10.                 Employee emp = new Employee();  
  11.                 emp.EmpID = 1;  
  12.                 emp.Name = "Gnanavel Sekar";  
  13.                 emp.Designation = "Sr.Software Engineer";  
  14.                 Contact contact = new Contact();  
  15.                 contact.EmpID = 1;  
  16.                 contact.Address = "test";  
  17.                 contact.Email = "[email protected]";  
  18.                 contact.MobileNo = "9876543210";  
  19.                 EmployeeContact_ViewModel viewModel = new EmployeeContact_ViewModel() {  
  20.                     contactDetails = contact,  
  21.                         employeeDetails = emp  
  22.                 };  
  23.                 return View(viewModel);  
  24.             }  
  25.             [HttpPost]  
  26.         public ActionResult LoadEmployees(EmployeeContact_ViewModel viewModel) {  
  27.             return View();  
  28.         }  
  29.     }  
  30. }  
View (LoadEmployee.cshtml)
  1. @model ViewModelUsingjQueryAjax.Models.EmployeeContact_ViewModel  
  2. @ {  
  3.     ViewBag.Title = "LoadEmployees";  
  4. } < script src = "http://code.jQuery.com/jquery-1.11.3.min.js" > < /script> < script type = "text/javascript" > $(document).ready(function() {  
  5.     $("#btnViewModel").click(function() {  
  6.         var employeeDetails = {  
  7.             EmpID: $('#@Html.IdFor(m=>m.employeeDetails.EmpID)').val(),  
  8.             Name: $('#@Html.IdFor(m=>m.employeeDetails.Name)').val(),  
  9.             Designation: $('#@Html.IdFor(m=>m.employeeDetails.Designation)').val()  
  10.         }  
  11.         var contactDetails = {  
  12.             MobileNo: $('#@Html.IdFor(m=>m.contactDetails.MobileNo)').val(),  
  13.             Address: $('#@Html.IdFor(m=>m.contactDetails.Address)').val(),  
  14.             Email: $('#@Html.IdFor(m=>m.contactDetails.Email)').val(),  
  15.             EmpID: $('#@Html.IdFor(m=>m.employeeDetails.EmpID)').val(),  
  16.         }  
  17.         var viewModel = {  
  18.             "employeeDetails": employeeDetails,  
  19.             "contactDetails": contactDetails  
  20.         }  
  21.         $.ajax({  
  22.             type: "post",  
  23.             url: "/Demo/LoadEmployees",  
  24.             data: viewModel,  
  25.             datatype: "json",  
  26.             cache: false,  
  27.             success: function(data) {  
  28.                 alert("View Model Passed Successfully");  
  29.             },  
  30.             error: function(xhr) {  
  31.                 alert('No Valid Data');  
  32.             }  
  33.         });  
  34.     });  
  35. }); < /script>  
  36. @using(Html.BeginForm()) {  
  37.     @Html.AntiForgeryToken() < div class = "form-horizontal" > < h4 > Employee < /h4> < hr / > @Html.ValidationSummary(true""new {  
  38.         @class = "text-danger"  
  39.     }) < div class = "form-group" > @Html.LabelFor(model => model.employeeDetails.EmpID, htmlAttributes: new {  
  40.         @class = "control-label col-md-2"  
  41.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.employeeDetails.EmpID, new {  
  42.         htmlAttributes = new {  
  43.             @class = "form-control"  
  44.         }  
  45.     })  
  46.     @Html.ValidationMessageFor(model => model.employeeDetails.EmpID, ""new {  
  47.         @class = "text-danger"  
  48.     }) < /div> < /div> < div class = "form-group" > @Html.LabelFor(model => model.employeeDetails.Name, htmlAttributes: new {  
  49.         @class = "control-label col-md-2"  
  50.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.employeeDetails.Name, new {  
  51.         htmlAttributes = new {  
  52.             @class = "form-control"  
  53.         }  
  54.     })  
  55.     @Html.ValidationMessageFor(model => model.employeeDetails.Name, ""new {  
  56.         @class = "text-danger"  
  57.     }) < /div> < /div> < div class = "form-group" > @Html.LabelFor(model => model.employeeDetails.Designation, htmlAttributes: new {  
  58.         @class = "control-label col-md-2"  
  59.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.employeeDetails.Designation, new {  
  60.         htmlAttributes = new {  
  61.             @class = "form-control"  
  62.         }  
  63.     })  
  64.     @Html.ValidationMessageFor(model => model.employeeDetails.Designation, ""new {  
  65.         @class = "text-danger"  
  66.     }) < /div> < /div> < h4 > Contact < /h4> < hr / > @Html.ValidationSummary(true""new {  
  67.         @class = "text-danger"  
  68.     }) < div class = "form-group" > @Html.LabelFor(model => model.contactDetails.MobileNo, htmlAttributes: new {  
  69.         @class = "control-label col-md-2"  
  70.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.contactDetails.MobileNo, new {  
  71.         htmlAttributes = new {  
  72.             @class = "form-control"  
  73.         }  
  74.     })  
  75.     @Html.ValidationMessageFor(model => model.contactDetails.MobileNo, ""new {  
  76.         @class = "text-danger"  
  77.     }) < /div> < /div> < div class = "form-group" > @Html.LabelFor(model => model.contactDetails.Address, htmlAttributes: new {  
  78.         @class = "control-label col-md-2"  
  79.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.contactDetails.Address, new {  
  80.         htmlAttributes = new {  
  81.             @class = "form-control"  
  82.         }  
  83.     })  
  84.     @Html.ValidationMessageFor(model => model.contactDetails.Address, ""new {  
  85.         @class = "text-danger"  
  86.     }) < /div> < /div> < div class = "form-group" > @Html.LabelFor(model => model.contactDetails.Email, htmlAttributes: new {  
  87.         @class = "control-label col-md-2"  
  88.     }) < div class = "col-md-10" > @Html.EditorFor(model => model.contactDetails.Email, new {  
  89.         htmlAttributes = new {  
  90.             @class = "form-control"  
  91.         }  
  92.     })  
  93.     @Html.ValidationMessageFor(model => model.contactDetails.Email, ""new {  
  94.         @class = "text-danger"  
  95.     }) < /div> < /div> < div class = "form-group" > < div class = "col-md-offset-2 col-md-10" > < input type = "button"  
  96.     id = "btnViewModel"  
  97.     value = "Create"  
  98.     class = "btn btn-default" / > < /div> < /div> < /div>  
  99. } < div > @Html.ActionLink("Back to List""Index") < /div>  
Refer to the attached project for reference and I did attach the demonstrated project without package due to the size limit.
 
Summary
 
In this article, we discussed how to work with ViewModel in ASP.NET MVC5 Using jQuery Ajax and Strongly Typed View.
 
I hope it will help you out. Your valuable feedback and comments about this article are always welcome. 


Similar Articles