Binding View With Model Using Enterprise Library In ASP.NET MVC 5

I am using Microsoft Enterprise Library to perform the database operation. Microsoft provides this library to perform the database operations which is very flexible to use with the web application.

So, let’s start with the following procedure:
  • Creating Solution
  • Perform Database Operation
  • Working with Microsoft Enterprise Library
  • Binding Model with View
  • Binding Data with View using jQuery

Prerequisites

There are the following prerequisite before getting started with the scenario,

  • Visual Studio 2013 or Visual Studio 2015

Note: I am creating this project in Visual Studio 2015.

Creating Solution

In this section we will create a blank solution and in the blank solution we will categorize the project into different categories as “Web”, “Models” and “Infrastructure”. In the Web folder we will create the web application with the help of ASP.NET MVC 5 Project Template and in the rest two solution folders we will create the “Class Library” for Models and “Core” for database operations. So let’s start with the following steps:

Step 1: Open Visual Studio 2015 and click on “New Project”,

Visual Studio Start Page
                                             Figure 1: Visual Studio Start Page

Step 2:
Select Visual Studio Solutions from the left pane and select the “Blank Solution” named “CricketMasters”.

Creating Blank Solution
                                                                     Figure 2: Creating Blank Solution

Step 3: Right click on the “CricketMasters” from the Solution Explorer and add a “New Solution Folder” named “Web”,

Adding New Solution Folder
                                                   Figure 3: Adding New Solution Folder

Create two more solutions folder named “Infrastructure” and “Models”.

Step 4: Right click on the “Web” folder and select “New” and click “Add New Project”,

Adding New Project In Solution
                                       Figure 4: Adding New Project In Solution

Step 5:
Select the Web from the left pane in the next wizard and click on the “ASP.NET Web Application” to create web application named “CricketMastersWeb

Adding Web Application Project
                                                Figure 5: Adding Web Application Project

Step 6: In the next “ASP.NET” wizard select the “MVC Project Template” to create ASP.NET MVC Application.

MVC Project Template
                                                      Figure 6: MVC Project Template

Now your web project created successfully.

Perform Database Operation

In this section we will create the database for the application and tables with the records. We will create stored procedures for getting records from the database. Begin with the following steps:

Step 1:
Create a database with the following query:

  1. CREATE DATABASE Cricketer  
Step 2: Now, let’s execute the following SQL Script for creating table with the records and stored procedures:
  1. USE [Cricketer]  
  2. GO  
  3. /****** Object:  Table [dbo].[CricketerProfile]    Script Date: 12/13/2015 1:33:41 PM ******/  
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. SET ANSI_PADDING ON  
  9. GO  
  10. IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CricketerProfile]'AND type in (N'U'))  
  11. BEGIN  
  12. CREATE TABLE [dbo].[CricketerProfile](  
  13.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  14.     [Name] [varchar](50) NULL,  
  15.     [ODI] [intNULL,  
  16.     [Tests] [intNULL,  
  17.     [ODIRuns] [intNULL,  
  18.     [TestRuns] [intNULL,  
  19.  CONSTRAINT [PK_CricketerProfile] PRIMARY KEY CLUSTERED   
  20. (  
  21.     [ID] ASC  
  22. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  23. ON [PRIMARY]  
  24. END  
  25. GO  
  26. SET ANSI_PADDING OFF  
  27. GO  
  28. SET IDENTITY_INSERT [dbo].[CricketerProfile] ON   
  29.   
  30. GO  
  31. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES (1, N'Sachin Tendulkar', 463, 200, 18426, 15921)  
  32. GO  
  33. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES (2, N'Saurav Ganguly', 311, 113, 11363, 7212)  
  34. GO  
  35. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES (3, N'Rahul Dravid', 344, 164, 10889, 13228)  
  36. GO  
  37. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES (4, N'V.V.S. Laxman', 86, 134, 2338, 8781)  
  38. GO  
  39. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns]) VALUES (5, N'Virendar Sehwag', 251, 104, 8273, 8586)  
  40. GO  
  41. SET IDENTITY_INSERT [dbo].[CricketerProfile] OFF  
  42. GO  
  43. /****** Object:  StoredProcedure [dbo].[CC_GetCricketerDetailsById]    Script Date: 12/13/2015 1:33:41 PM ******/  
  44. SET ANSI_NULLS ON  
  45. GO  
  46. SET QUOTED_IDENTIFIER ON  
  47. GO  
  48. IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CC_GetCricketerDetailsById]'AND type in (N'P', N'PC'))  
  49. BEGIN  
  50. EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[CC_GetCricketerDetailsById] AS'   
  51. END  
  52. GO  
  53. ALTER Proc [dbo].[CC_GetCricketerDetailsById]  
  54. @ID int  
  55. AS  
  56. Begin  
  57.     select * from CricketerProfile (NOLOCK) where ID = @Id  
  58. End  
  59.   
  60. GO  
  61. /****** Object:  StoredProcedure [dbo].[CC_GetCricketerList]    Script Date: 12/13/2015 1:33:41 PM ******/  
  62. SET ANSI_NULLS ON  
  63. GO  
  64. SET QUOTED_IDENTIFIER ON  
  65. GO  
  66. IF NOT EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[CC_GetCricketerList]'AND type in (N'P', N'PC'))  
  67. BEGIN  
  68. EXEC dbo.sp_executesql @statement = N'CREATE PROCEDURE [dbo].[CC_GetCricketerList] AS'   
  69. END  
  70. GO  
  71. ALTER Proc [dbo].[CC_GetCricketerList]  
  72. AS  
  73. Begin  
  74.     select ID,Name from CricketerProfile (NOLOCK)  
  75. End  
  76. GO  
Working with Microsoft Enterprise Library

In this section we will install the Microsoft Enterprise Library from the Manage NuGet Packages in the “CricketMasters.Core” project and create the class library for the web application. So, let’s start with the following steps:

Step 1: In the Solution Explorer, right click on the Models and add a “Class Library Project” by clicking on “New Project” in the Add sub menu as “CricketMasters.Models

Adding Class Library Project
                                                   Figure 7: Adding Class Library Project

Step 2: Add a new class in the Models project.

Adding New Class in Project
                                                   Figure 8: Adding New Class in Project

Step 3: Replace the class with the following code of class:
  1. namespace CricketMasters.Models  
  2. {  
  3.     #region Cricketer Class  
  4.     /// <summary>  
  5.     /// This class is used for the cricketers  
  6.     /// </summary>  
  7.     public class Cricketer  
  8.     {  
  9.         #region Properties  
  10.         /// <summary>  
  11.         /// get and set the ID  
  12.         /// </summary>  
  13.         public int ID { getset; }  
  14.         /// <summary>  
  15.         /// get and set the Name  
  16.         /// </summary>  
  17.         public string Name { getset; }  
  18.         /// <summary>  
  19.         /// get and set the ODI  
  20.         /// </summary>  
  21.         public int ODI { getset; }  
  22.         /// <summary>  
  23.         /// get and set the Tests  
  24.         /// </summary>  
  25.         public int Tests { getset; }  
  26.         /// <summary>  
  27.         /// get and set the OdiRuns  
  28.         /// </summary>  
  29.         public int OdiRuns { getset; }  
  30.         /// <summary>  
  31.         /// get and set the TestRuns  
  32.         /// </summary>  
  33.         public int TestRuns { getset; }  
  34.         /// <summary>  
  35.         /// get and set the Cricketers  
  36.         /// </summary>  
  37.         public List<Cricketer> Cricketers { getset; }  
  38.         #endregion  
  39.     }  
  40.     #endregion  
  41. }  
Note: Build the solution.

Step 4: In the Solution Explorer, right click on the Infrastructure folder and add a “New Project” named “CricketMasters.Core”.

Step 5: Right click on the project in the Infrastructure folder and add two new folders names“BLL” and “DAL”.

Adding New Folder in Project
                                          Figure 9: Adding New Folder in Project

Step 6: Right click on the “References” in the core project and add a reference of the Models project.

Adding Model Reference
                                                   Figure 10: Adding Model Reference

Step 7: Right click on the core project and click on “Manage NuGet Packages

Adding NuGet Package
      Figure 11: Adding NuGet Package

Step 8: Search “Enterprise Library” and install the library,

Adding Microsoft Enterprise Library
                                                Figure 12: Adding Microsoft Enterprise Library

Step 9: Add a class in the DAL folder.

Adding New Class in Folder
                                             Figure 13: Adding New Class in Folder

Step 10: Replace the DAL class code with the following code:
  1. using CricketMasters.Models;  
  2. using Microsoft.Practices.EnterpriseLibrary.Data;  
  3. using Microsoft.Practices.EnterpriseLibrary.Data.Sql;  
  4. using System;  
  5. using System.Collections.Generic;  
  6. using System.Configuration;  
  7. using System.Data;  
  8. using System.Data.Common;  
  9. using System.Linq;  
  10. using System.Reflection;  
  11.   
  12. namespace CricketMasters.Core.DAL  
  13. {  
  14.     #region Cricketer DAL  
  15.     /// <summary>  
  16.     /// This class is used for Cricketer Data Access Class  
  17.     /// </summary>  
  18.     public class CricketerDAL  
  19.     {  
  20.         #region Variable    
  21.         /// <summary>    
  22.         /// Specify the Database variable    
  23.         /// </summary>    
  24.         Database objDB;  
  25.         /// <summary>    
  26.         /// Specify the static variable    
  27.         /// </summary>    
  28.         static string ConnectionString;  
  29.         #endregion  
  30.  
  31.         #region Constructor    
  32.         /// <summary>    
  33.         /// This constructor is used to get the connectionstring from the config file    
  34.         /// </summary>    
  35.         public CricketerDAL()  
  36.         {  
  37.             ConnectionString = ConfigurationManager.ConnectionStrings["CricketerConnectionString"].ToString();  
  38.         }  
  39.         #endregion  
  40.  
  41.         #region Database Method    
  42.         public List<T> ConvertTo<T>(DataTable datatable) where T : new()  
  43.         {  
  44.             List<T> Temp = new List<T>();  
  45.             try  
  46.             {  
  47.                 List<string> columnsNames = new List<string>();  
  48.                 foreach (DataColumn DataColumn in datatable.Columns)  
  49.                     columnsNames.Add(DataColumn.ColumnName);  
  50.                 Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));  
  51.                 return Temp;  
  52.             }  
  53.             catch  
  54.             {  
  55.                 return Temp;  
  56.             }  
  57.         }  
  58.         public T getObject<T>(DataRow row, List<string> columnsName) where T : new()  
  59.         {  
  60.             T obj = new T();  
  61.             try  
  62.             {  
  63.                 string columnname = "";  
  64.                 string value = "";  
  65.                 PropertyInfo[] Properties;  
  66.                 Properties = typeof(T).GetProperties();  
  67.                 foreach (PropertyInfo objProperty in Properties)  
  68.                 {  
  69.                     columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());  
  70.                     if (!string.IsNullOrEmpty(columnname))  
  71.                     {  
  72.                         value = row[columnname].ToString();  
  73.                         if (!string.IsNullOrEmpty(value))  
  74.                         {  
  75.                             if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)  
  76.                             {  
  77.                                 value = row[columnname].ToString().Replace("$""").Replace(",""");  
  78.                                 objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);  
  79.                             }  
  80.                             else  
  81.                             {  
  82.                                 value = row[columnname].ToString();  
  83.                                 objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);  
  84.                             }  
  85.                         }  
  86.                     }  
  87.                 }  
  88.                 return obj;  
  89.             }  
  90.             catch (Exception ex)  
  91.             {  
  92.                 return obj;  
  93.             }  
  94.         }  
  95.         #endregion  
  96.  
  97.         #region College    
  98.         /// <summary>    
  99.         /// This method is used to get the cricketer data    
  100.         /// </summary>    
  101.         /// <returns></returns>    
  102.         public List<Cricketer> GetCricketerList()  
  103.         {  
  104.             List<Cricketer> objGetCricketers = null;  
  105.             objDB = new SqlDatabase(ConnectionString);  
  106.             using (DbCommand objcmd = objDB.GetStoredProcCommand("CC_GetCricketerList"))  
  107.             {  
  108.                 try  
  109.                 {  
  110.                     using (DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0])  
  111.                     {  
  112.                         objGetCricketers = ConvertTo<Cricketer>(dataTable);  
  113.                     }  
  114.                 }  
  115.                 catch (Exception ex)  
  116.                 {  
  117.                     throw ex;  
  118.                     return null;  
  119.                 }  
  120.             }  
  121.             return objGetCricketers;  
  122.         }  
  123.   
  124.         /// <summary>  
  125.         /// This method is used to get cricketers details by cricketer id  
  126.         /// </summary>  
  127.         /// <returns></returns>  
  128.         public List<Cricketer> GetCricketerDetailsById(int Id)  
  129.         {  
  130.             List<Cricketer> objCricketerDetails = null;  
  131.             objDB = new SqlDatabase(ConnectionString);  
  132.             using (DbCommand objcmd = objDB.GetStoredProcCommand("CC_GetCricketerDetailsById"))  
  133.             {  
  134.                 try  
  135.                 {  
  136.                     objDB.AddInParameter(objcmd, "@ID", DbType.Int32, Id);  
  137.   
  138.                     using (DataTable dataTable = objDB.ExecuteDataSet(objcmd).Tables[0])  
  139.                     {  
  140.                         objCricketerDetails = ConvertTo<Cricketer>(dataTable);  
  141.                     }  
  142.                 }  
  143.                 catch (Exception ex)  
  144.                 {  
  145.                     throw ex;  
  146.                     return null;  
  147.                 }  
  148.             }  
  149.             return objCricketerDetails;  
  150.         }  
  151.         #endregion  
  152.     }  
  153.     #endregion  
  154. }  
Step 11: Now add a class in the BLL folder named “CricketerBL” and add the following code in the class:
  1. using CricketMasters.Core.DAL;  
  2. using CricketMasters.Models;  
  3. using System;  
  4. using System.Collections.Generic;  
  5.   
  6. namespace CricketMasters.Core.BLL  
  7. {  
  8.     public class CricketerBL  
  9.     {  
  10.         public List<Cricketer> GetCricketerList()  
  11.         {  
  12.             List<Cricketer> ObjCricketers = null;  
  13.             try  
  14.             {  
  15.                 ObjCricketers = new CricketerDAL().GetCricketerList();  
  16.             }  
  17.             catch (Exception)  
  18.             {  
  19.   
  20.                 throw;  
  21.             }  
  22.             return ObjCricketers;  
  23.         }  
  24.         /// <summary>  
  25.         /// This method is used to get cricketers details by cricketer id  
  26.         /// </summary>  
  27.         /// <returns></returns>        
  28.         public List<Cricketer> GetCricketerDetailsById(int Id)  
  29.         {  
  30.             List<Cricketer> ObjCricketerDetails = null;  
  31.             try  
  32.             {  
  33.                 ObjCricketerDetails = new CricketerDAL().GetCricketerDetailsById(Id);  
  34.             }  
  35.             catch (Exception)  
  36.             {  
  37.   
  38.                 throw;  
  39.             }  
  40.             return ObjCricketerDetails;  
  41.         }  
  42.     }  
  43. }  
Step 12: Build the solution.

Binding Model with View

In this section we will create the empty MVC 5 controller and add a view for displaying the details. We will also bind the view from the data by passing the data from the model to the controller. So, let’s begin with the following steps:

Step 1: In the Web Project, right click on the Controllers folder go to Add and click on the “New Scaffolded Item

Adding New Scaffolded Item
                                             Figure 14: Adding New Scaffolded Item

Step 2: In the next wizard, select the “MVC 5 Empty Controller”.

Add Scaffold Wizard
                                                         Figure 15: Add Scaffold Wizard

Specify the controller name as “CricketersController

Adding New Controller
                                             Figure 16: Adding New Controller

Step 3: Add a reference of Models and Core Project in the Web Project.

Step 4: In the CricketersController, replace the code with the following code:
  1. using CricketMasters.Core.BLL;  
  2. using CricketMasters.Models;  
  3. using System;  
  4. using System.Collections.Generic;  
  5. using System.Linq;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace CricketMastersWeb.Controllers  
  9. {  
  10.     public class CricketersController : Controller  
  11.     {  
  12.         #region Variable  
  13.         /// <summary>  
  14.         /// This varaible is used for Cricketer BL  
  15.         /// </summary>  
  16.         public CricketerBL cricketerBL;  
  17.         #endregion  
  18.  
  19.         #region Cricketer  
  20.         /// <summary>  
  21.         /// This method is used to get all cricketer names  
  22.         /// </summary>  
  23.         /// <returns></returns>  
  24.         [HttpGet, ActionName("GetAllCricketer")]  
  25.         public ActionResult GetAllCricketer()  
  26.         {  
  27.             List<Cricketer> objCricketer = new List<Cricketer>();  
  28.   
  29.             var response = new CricketerBL().GetCricketerList();  
  30.             if (!object.Equals(response, null))  
  31.             {  
  32.                 objCricketer = response.ToList();  
  33.             }  
  34.             return View("~/Views/Cricketers/Cricketer.cshtml"new Cricketer { Cricketers = objCricketer });  
  35.         }  
  36.         #endregion  
  37.     }  
  38. }  
In the above code, there is an action method which is used to get all cricketer names from the database. You can see that there is a highlighted code, that code is used to bind the model with the cricketer names which is further used to bind the cricketer names in the dropdownlist.

Step 5: Now add a view, by right click on the Views, then Cricketers

Adding View
                                                         Figure 17: Adding View

Step 6: Replace the view code with the following code:
  1. @model CricketMasters.Models.Cricketer  
  2. @{  
  3.     ViewBag.Title = "Cricketer";  
  4. }  
  5.   
  6. <h2>Cricketer  Statistics</h2>  
  7.   
  8. <div class="row">  
  9.     <div class="col-md-8">  
  10.         <hr />  
  11.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  12.         <div class="form-group">  
  13.             @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })  
  14.             <div class="col-md-10">  
  15.                 @Html.DropDownListFor(m => m.Name, new SelectList(Model.Cricketers, "ID""Name"), new { @id = "playerNameList", @class = "form-control" })  
  16.             </div>  
  17.         </div>  
  18.     </div>  
  19. </div>  
Step 7: Go to the Web.Config file of the Web application and add the following connection string in the Connection Strings tab:
  1. <add name="CricketerConnectionString" connectionString="Data Source=Your Server Name;Initial Catalog=Cricketer;User ID=Your User ID;Password=Your Password" providerName="System.Data.SqlClient" />  
Note: Please replace the highlighted code with your server credentials.

Step 8: Build the solution and now open Views, Shared, then _Layout.cshtml file and change the code with the highlighted code below:
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title - Cricket Masters Application</title>  
  7.     @Styles.Render("~/Content/css")  
  8.     @Scripts.Render("~/bundles/modernizr")  
  9.   
  10. </head>  
  11. <body>  
  12.     <div class="navbar navbar-inverse navbar-fixed-top">  
  13.         <div class="container">  
  14.             <div class="navbar-header">  
  15.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  16.                     <span class="icon-bar"></span>  
  17.                     <span class="icon-bar"></span>  
  18.                     <span class="icon-bar"></span>  
  19.                 </button>  
  20.                 @Html.ActionLink("Cricket Masters""Index""Home"new { area = "" }, new { @class = "navbar-brand" })  
  21.             </div>  
  22.             <div class="navbar-collapse collapse">  
  23.                 <ul class="nav navbar-nav">  
  24.                     <li>@Html.ActionLink("Home""Index""Home")</li>  
  25.                     <li>@Html.ActionLink("About""About""Home")</li>  
  26.                     <li>@Html.ActionLink("Contact""Contact""Home")</li>  
  27.                     <li>@Html.ActionLink("Cricketers""GetAllCricketer""Cricketers")</li>  
  28.                 </ul>  
  29.                 @Html.Partial("_LoginPartial")  
  30.             </div>  
  31.         </div>  
  32.     </div>  
  33.     <div class="container body-content">  
  34.         @RenderBody()  
  35.         <hr />  
  36.         <footer>  
  37.             <p>© @DateTime.Now.Year - Cricket Masters</p>  
  38.         </footer>  
  39.     </div>  
  40.   
  41.     @Scripts.Render("~/bundles/jquery")  
  42.     @Scripts.Render("~/bundles/bootstrap")  
  43.     @RenderSection("scripts", required: false)  
  44. </body>  
  45. </html>  
Step 9: Now run the project. Click on the Cricketers link to open the view as in the following,

Opening View in MVC 5
                                                         Figure 18: Opening View in MVC 5

When you click on the “Cricketers” link, you can see that your DropDownList has the values which has been passed using the model. Take a look.

Binding Data in DropDownList Using Model
                                       Figure 19: Binding Data in DropDownList Using Model

Binding Data with View using jQuery

In this section we will bind the details of the particular player in the table. We will use jQuery to send the id to the database to fetch the details of the player. So, let’s begin with the following steps:

Step 1: Add the following method in the “CricketersController”.
  1. /// <summary>  
  2. /// This method is used to get all cricketer details based on the cricketer id  
  3. /// </summary>  
  4. /// <param name="CricketerId"></param>  
  5. /// <returns></returns>  
  6. [HttpGet, ActionName("GetCricketerDetailsById")]  
  7. public JsonResult GetCricketerDetailsById(int CricketerId)  
  8. {  
  9.     List<Cricketer> objCricketerDetails = new List<Cricketer>();  
  10.   
  11.     var response = new CricketerBL().GetCricketerDetailsById(CricketerId);  
  12.     if (!object.Equals(response, null))  
  13.     {  
  14.         objCricketerDetails = response.ToList();  
  15.     }  
  16.     return Json(objCricketerDetails, JsonRequestBehavior.AllowGet);  
  17. }  
In the above method we get the details of the individual player and pass the data to the view in the JSON format.

Step 2: By adding the elements of table data your final view code is as in the following,
  1. @model CricketerApp.Model.Cricketer  
  2. @{  
  3.     ViewBag.Title = "Cricketer";  
  4. }  
  5. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  6. <h2>Cricketer  Statistics</h2>  
  7.   
  8. <div class="row">  
  9.     <div class="col-md-8">  
  10.         <hr />  
  11.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  12.         <div class="form-group">  
  13.             @Html.LabelFor(m => m.Name, new { @class = "col-md-2 control-label" })  
  14.             <div class="col-md-10">  
  15.                 @Html.DropDownListFor(m => m.Name, new SelectList(Model.Cricketers, "ID""Name"), new { @id = "playerNameList", @class = "form-control"@Onchange = "return GetCricketerDetails();" })  
  16.             </div>  
  17.         </div>  
  18.     </div>  
  19. </div><br />  
  20. <div class="row">  
  21.     <div class="form-group">  
  22.         <div id="CricketerList" class="col-md-8"></div>  
  23.     </div>  
  24. </div>  
  25.   
  26. <script type="text/javascript">  
  27.     $(document).ready(function () {  
  28.         GetCricketerDetails();  
  29.     });  
  30.   
  31.     function GetCricketerDetails() {  
  32.         var cricketerId = $('#playerNameList option:selected').val();  
  33.         $.ajax({  
  34.             url: '@Url.Action("GetCricketerDetailsById", "Cricketers")',  
  35.             type: "GET",  
  36.             dataType: "json",  
  37.             data: { CricketerId: cricketerId },  
  38.             success: function (data) {  
  39.                 $('#CricketerList').html(" ");  
  40.                 var html = "";  
  41.                 html += "<table class=\"table\">";  
  42.                 html += "<tr>";  
  43.                 html += "<th>";  
  44.                 html += "@Html.DisplayNameFor(model=>model.Name)";  
  45.                 html += "</th>";  
  46.                 html += "<th>";  
  47.                 html += "@Html.DisplayNameFor(model=>model.ODI)";  
  48.                 html += "</th>";  
  49.                 html += "<th>";  
  50.                 html += "@Html.DisplayNameFor(model=>model.Tests)";  
  51.                 html += "</th>";  
  52.                 html += "<th>";  
  53.                 html += "@Html.DisplayNameFor(model=>model.OdiRuns)";  
  54.                 html += "</th>";  
  55.                 html += "<th>";  
  56.                 html += "@Html.DisplayNameFor(model=>model.TestRuns)";  
  57.                 html += "</th>";  
  58.                 html += "</tr>";  
  59.                 $.each(data, function (index, item) {  
  60.                     html += "<tr>";  
  61.                     html += "<td>";  
  62.                     html += "<lable>" + item.Name + "</lable>"  
  63.                     html += "</td>";  
  64.                     html += "<td>";  
  65.                     html += "<lable>" + item.ODI + "</lable>"  
  66.                     html += "</td>";  
  67.                     html += "<td>";  
  68.                     html += "<lable>" + item.Tests + "</lable>"  
  69.                     html += "</td>";  
  70.                     html += "<td>";  
  71.                     html += "<lable>" + item.OdiRuns+ "</lable>"  
  72.                     html += "</td>";  
  73.                     html += "<td>";  
  74.                     html += "<lable>" + item.TestRuns + "</lable>"  
  75.                     html += "</td>";  
  76.                     html += "</tr>";  
  77.                     html += "</table>";  
  78.                 });  
  79.                 $('#CricketerList').append(html);  
  80.             }  
  81.         });  
  82.         return false;  
  83.     }  
  84. </script>  
Step 3: Save the page and run the project. You can see in the following screenshot that the data is bind to the table.

Binding Data in View using jQuery
                                             Figure 20: Binding Data in View using jQuery

You can now change the selection and you will get the output.

Binding Data in View in MVC 5
                                                   Figure 21: Binding Data in View in MVC 5

That’s it.

Summary

This article described how to bind the data to the view by passing the model in the controller. We also learned to bind the data using the jQuery to the table in the View. Thanks for reading the article. 

Up Next
    Ebook Download
    View all
    Learn
    View all