MVC 5 - Partial View With Pagination In jQuery Dialog

Hello folks,

Today, we will discuss about the development in ASP.NET MVC 5. We can develop a particular task with the different ways as we can present the data in the user interface in the form of tables, GridViews, etc. Some time ago, I was working on a project and in that I had to show the data in the partial view which I successfully did. Subsequently, I also wrote an article as Paging, Sorting, And Filtering With Partial View In ASP.NET MVC 5 to show the data with the help of partial view.

I represented the paging in the main view and some small info, related to main view data, was presented in the partial view. In this article, we’ll display the data and perform paging in jQuery dialog with the help of partial view or we can say that we’ll pass the data in the partial view and represent it in jQuery dialog.

Getting Started

To start on this article, you must have the knowledge of MVC. There are some following prerequisites before start working on this.
  • Visual Studio 2012 or later
  • MVC 4 or later

So, let’s start with the following procedure,

  • Creating solution
  • Perform database operation
  • Working with Microsoft Enterprise Library
  • Creating User Interface
  • Binding partial view with jQuery dialog

Creating Solution

In this section, we’ll create the project infrastructure. Thus, follow the steps given below to start.

Step 1

In Visual Studio 2013 Start screen, just click New Project.


Figure 1: Visual Studio Start Page

Step 2

In the next wizard, select the “Web” from the left pane and select ASP.NET Web Application”. Enter the relative name of the project.


Figure 2: Create New Project

Step 3

In the next wizard, select MVC Project Template to create MVC project.


Figure 3: One ASP.Net Wizard

Now, your Web Application has created successfully.

Perform Database Operation

In this section, we’ll deal with our database. We will create the database according to the situation or you can use your database for the further operation. Follow the steps given below to perform the database operation.

Step 1

Create the database first from the following query.

  1. CREATE DATABASE Cricketer  
Step 2

Now, let’s execute the query given below to proceed ahead.
  1. USE [Cricketer]  
  2. GO  
  3.   
  4. SET ANSI_NULLS ON  
  5. GO  
  6. SET QUOTED_IDENTIFIER ON  
  7. GO  
  8. SET ANSI_PADDING ON  
  9. GO  
  10. CREATE TABLE [dbo].[CricketerProfile](  
  11.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  12.     [Name] [varchar](50) NULL,  
  13.     [ODI] [intNULL,  
  14.     [Tests] [intNULL,  
  15.     [ODIRuns] [intNULL,  
  16.     [TestRuns] [intNULL,  
  17.     [Team] [intNULL,  
  18.  CONSTRAINT [PK_CricketerProfile] PRIMARY KEY CLUSTERED   
  19. (  
  20.     [ID] ASC  
  21. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  22. ON [PRIMARY]  
  23.   
  24. GO  
  25. SET ANSI_PADDING OFF  
  26. GO  
  27. SET ANSI_NULLS ON  
  28. GO  
  29. SET QUOTED_IDENTIFIER ON  
  30. GO  
  31. SET ANSI_PADDING ON  
  32. GO  
  33. CREATE TABLE [dbo].[Team](  
  34.     [ID] [int] IDENTITY(1,1) NOT NULL,  
  35.     [Name] [varchar](50) NULL,  
  36. PRIMARY KEY CLUSTERED   
  37. (  
  38.     [ID] ASC  
  39. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  40. ON [PRIMARY]  
  41.   
  42. GO  
  43. SET ANSI_PADDING OFF  
  44. GO  
  45. SET IDENTITY_INSERT [dbo].[CricketerProfile] ON   
  46.   
  47. GO  
  48. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (1, N'Sachin Tendulkar', 463, 200, 18426, 15921, 1)  
  49. GO  
  50. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (2, N'Saurav Ganguly', 311, 113, 11363, 7212, 1)  
  51. GO  
  52. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (3, N'Rahul Dravid', 344, 164, 10889, 13228, 1)  
  53. GO  
  54. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (4, N'V.V.S. Laxman', 86, 134, 2338, 8781, 1)  
  55. GO  
  56. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (5, N'Virendar Sehwag', 251, 104, 8273, 8586, 1)  
  57. GO  
  58. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (6, N'Yuvraj Singh', 293, 40, 8329, 1900, 1)  
  59. GO  
  60. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (7, N'M. S. Dhoni', 283, 90, 9110, 4876, 1)  
  61. GO  
  62. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (8, N'Virat Kohli', 176, 53, 7570, 4209, 1)  
  63. GO  
  64. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (9, N'Harbhajan Singh', 236, 103, 1237, 2225, 1)  
  65. GO  
  66. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (10, N'Anil Kumble', 271, 132, 938, 2506, 1)  
  67. GO  
  68. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (11, N'Gautam Gambhir', 147, 58, 5238, 4154, 1)  
  69. GO  
  70. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (12, N'Rohit Sharma', 153, 21, 5131, 1184, 1)  
  71. GO  
  72. SET IDENTITY_INSERT [dbo].[CricketerProfile] OFF  
  73. GO  
  74. SET IDENTITY_INSERT [dbo].[Team] ON   
  75.   
  76. GO  
  77. INSERT [dbo].[Team] ([ID], [Name]) VALUES (1, N'India')  
  78. GO  
  79. INSERT [dbo].[Team] ([ID], [Name]) VALUES (2, N'Australia')  
  80. GO  
  81. INSERT [dbo].[Team] ([ID], [Name]) VALUES (3, N'New Zeland')  
  82. GO  
  83. INSERT [dbo].[Team] ([ID], [Name]) VALUES (4, N'South Africa')  
  84. GO  
  85. INSERT [dbo].[Team] ([ID], [Name]) VALUES (5, N'West Indies')  
  86. GO  
  87. SET IDENTITY_INSERT [dbo].[Team] OFF  
  88. GO  
  89. SET ANSI_NULLS ON  
  90. GO  
  91. SET QUOTED_IDENTIFIER ON  
  92. GO  
  93. CREATE Proc [dbo].[BP_GetAllTeams]    
  94.    
  95. AS    
  96. Begin    
  97.     select * from Team (NOLOCK)  
  98. End    
  99. GO  
  100.   
  101. SET ANSI_NULLS ON  
  102. GO  
  103. SET QUOTED_IDENTIFIER ON  
  104. GO  
  105.   
  106. --EXEC [BP_GetPlayersByTeam] 1, 1 , 4  
  107.   
  108. CREATE PROC [dbo].[BP_GetPlayersByTeam]  
  109.     @TeamId INT ,  
  110.     @PageNumber INT ,  
  111.     @PageSize INT  
  112. AS  
  113.     BEGIN    
  114.                ;  
  115.         WITH    PlayerCte  
  116.                   AS ( SELECT   ID ,  
  117.                                 Name ,  
  118.                                 ODI ,  
  119.                                 Tests ,  
  120.                                 ODIRuns ,  
  121.                                 TestRuns  
  122.                        FROM     dbo.CricketerProfile (NOLOCK)  
  123.                        WHERE    Team = @TeamId  
  124.                      )  
  125.             SELECT  * ,  
  126.                     ( SELECT    COUNT(*)   
  127.                       FROM      PlayerCte  
  128.                     )AS TotalCount  
  129.             FROM    PlayerCte  
  130.             ORDER BY PlayerCte.ID  
  131.                     OFFSET @PageSize * ( @PageNumber - 1 ) ROWS  
  132.        FETCH NEXT @PageSize ROWS ONLY  
  133.         OPTION  ( RECOMPILE );      
  134.     END;    
  135. GO  
Working with Microsoft Enterprise Library

In this section, we will categorize our Application into two parts or three parts. We can create the separate project for the models, but here I am adding the models in the same project. Therefore, let’s make it simpler by the procedure.

Step 1

At first, right click on the solution and go to Add-> New Folder and named Infrastructure.


Figure 4: Adding New folder in the solution

Step 2

Add a “New Class Library Project” in the newly added folder as “BestPlayers.Core”.


Figure 5: Adding Class Library Project

Step 3

Now, add the three folders in the project as “BL”, “DAL”, “Models”.

Step 4

Add a class and name it as “Team” in the Models folder and replace the code with the code.
  1. namespace BestPlayers.Core.Models  
  2. {  
  3.     public class Team  
  4.     {  
  5.         #region Properties  
  6.         /// <summary>  
  7.         /// get and set the ID  
  8.         /// </summary>  
  9.         public int ID { get; set; }  
  10.         /// <summary>  
  11.         /// get and set the Name  
  12.         /// </summary>  
  13.         public string Name { get; set; }  
  14.         #endregion  
  15.     }  
  16.   
  17.     public class Players  
  18.     {  
  19.         #region Properties  
  20.         /// <summary>  
  21.         /// get and set the ID  
  22.         /// </summary>  
  23.         public int ID { get; set; }  
  24.         /// <summary>  
  25.         /// get and set the Name  
  26.         /// </summary>  
  27.         public string Name { get; set; }  
  28.         /// <summary>  
  29.         /// get and set the ODI  
  30.         /// </summary>  
  31.         public int ODI { get; set; }  
  32.         /// <summary>  
  33.         /// get and set the Tests  
  34.         /// </summary>  
  35.         public int Tests { get; set; }  
  36.         /// <summary>  
  37.         /// get and set the ODIRuns  
  38.         /// </summary>  
  39.         public int ODIRuns { get; set; }  
  40.         /// <summary>  
  41.         /// get and set the TestRuns  
  42.         /// </summary>  
  43.         public int TestRuns { get; set; }  
  44.         #endregion  
  45.     }  
  46. }  
Step 4

After building the project, just right click on the project and click Manage NuGet Packages.


Figure 6: Manage NuGet Package

Step 5

Now, add the reference of “Microsoft Enterprise Library” in Core project.


Figure 7: Adding Enterprise Library

Step 6

Now, add a class and name it as PlayersDAL in the DAL folder.


Figure 8: Adding Class

Step 7

Replace the code with the code given below.
  1. using BestPlayers.Core.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 BestPlayers.Core.DAL  
  13. {  
  14.     public class PlayersDAL  
  15.     {  
  16.         #region Variable  
  17.         /// <summary>  
  18.         /// variable for Database  
  19.         /// </summary>  
  20.         Database objDB;  
  21.         #endregion  
  22.  
  23.         #region Database Method  
  24.         public List<T> ConvertTo<T>(DataTable datatable) where T : new()  
  25.         {  
  26.             List<T> Temp = new List<T>();  
  27.             try  
  28.             {  
  29.                 List<string> columnsNames = new List<string>();  
  30.                 foreach (DataColumn DataColumn in datatable.Columns)  
  31.                     columnsNames.Add(DataColumn.ColumnName);  
  32.                 Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));  
  33.                 return Temp;  
  34.             }  
  35.             catch  
  36.             {  
  37.                 return Temp;  
  38.             }  
  39.   
  40.         }  
  41.         public T getObject<T>(DataRow row, List<string> columnsName) where T : new()  
  42.         {  
  43.             T obj = new T();  
  44.             try  
  45.             {  
  46.                 string columnname = "";  
  47.                 string value = "";  
  48.                 PropertyInfo[] Properties;  
  49.                 Properties = typeof(T).GetProperties();  
  50.                 foreach (PropertyInfo objProperty in Properties)  
  51.                 {  
  52.                     columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());  
  53.                     if (!string.IsNullOrEmpty(columnname))  
  54.                     {  
  55.                         value = row[columnname].ToString();  
  56.                         if (!string.IsNullOrEmpty(value))  
  57.                         {  
  58.                             if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)  
  59.                             {  
  60.                                 value = row[columnname].ToString().Replace("$""").Replace(",""");  
  61.                                 objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);  
  62.                             }  
  63.                             else  
  64.                             {  
  65.                                 value = row[columnname].ToString();  
  66.                                 objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);  
  67.                             }  
  68.                         }  
  69.                     }  
  70.                 }  
  71.                 return obj;  
  72.             }  
  73.             catch  
  74.             {  
  75.                 return obj;  
  76.             }  
  77.         }  
  78.         #endregion  
  79.   
  80.         /// <summary>  
  81.         /// This method is created to get all teams.  
  82.         /// </summary>  
  83.         /// <returns></returns>  
  84.         public List<Team> GetAllTeams()  
  85.         {  
  86.             List<Team> teams = new List<Team>();  
  87.             objDB = new SqlDatabase(ConfigurationManager.ConnectionStrings["PlayersConfiguration"].ConnectionString);  
  88.   
  89.             using (DbCommand objCMD = objDB.GetStoredProcCommand("BP_GetAllTeams"))  
  90.             {  
  91.                 try  
  92.                 {  
  93.                     using (DataTable dataTable = objDB.ExecuteDataSet(objCMD).Tables[0])  
  94.                     {  
  95.                         teams = ConvertTo<Team>(dataTable);  
  96.                     }  
  97.                 }  
  98.                 catch (Exception ex)  
  99.                 {  
  100.                     bool rethrow = false;  
  101.                     if (rethrow)  
  102.                     {  
  103.                         throw ex;  
  104.                     }  
  105.                     return null;  
  106.                 }  
  107.             }  
  108.             return teams;  
  109.         }  
  110.         /// <summary>  
  111.         /// This method is created to get players list on the basis of team id.  
  112.         /// </summary>  
  113.         /// <param name="TeamId"></param>  
  114.         /// <param name="page"></param>  
  115.         /// <param name="pageSize"></param>  
  116.         /// <returns></returns>  
  117.         public List<Players> GetPlayersByTeam(int TeamId, string page, string pageSize)  
  118.         {  
  119.             List<Players> players = null;  
  120.             objDB = new SqlDatabase(ConfigurationManager.ConnectionStrings["PlayersConfiguration"].ConnectionString);  
  121.   
  122.             using (DbCommand objCMD = objDB.GetStoredProcCommand("BP_GetPlayersByTeam"))  
  123.             {  
  124.                 try  
  125.                 {  
  126.                     objDB.AddInParameter(objCMD, "@TeamId", DbType.Int32, TeamId);  
  127.                     objDB.AddInParameter(objCMD, "@PageNumber", DbType.Int32, Convert.ToInt32(page));  
  128.                     objDB.AddInParameter(objCMD, "@PageSize", DbType.Int32, Convert.ToInt32(pageSize));  
  129.   
  130.                     using (DataTable dataTable = objDB.ExecuteDataSet(objCMD).Tables[0])  
  131.                     {  
  132.                         players = ConvertTo<Players>(dataTable);  
  133.                     }  
  134.                 }  
  135.                 catch (Exception ex)  
  136.                 {  
  137.                     bool rethrow = false;  
  138.                     if (rethrow)  
  139.                     {  
  140.                         throw ex;  
  141.                     }  
  142.                     return null;  
  143.                 }  
  144.             }  
  145.             return players;  
  146.         }  
  147.     }  
  148. }  
Step 8

Now, add a class and name it as PlayersBL in the BL folder and replace the code with the following code:
  1. using BestPlayers.Core.DAL;  
  2. using BestPlayers.Core.Models;  
  3. using System;  
  4. using System.Collections.Generic;  
  5.   
  6. namespace BestPlayers.Core.BL  
  7. {  
  8.     public class PlayersBL  
  9.     {  
  10.         /// <summary>  
  11.         /// This method is created to get all teams.  
  12.         /// </summary>  
  13.         /// <returns></returns>  
  14.         public List<Team> GetAllTeams()  
  15.         {  
  16.             List<Team> teams = null;  
  17.             try  
  18.             {  
  19.                 teams = new PlayersDAL().GetAllTeams();  
  20.             }  
  21.             catch (Exception ex)  
  22.             {  
  23.                 bool rethrow = false;                  
  24.                 if (rethrow)  
  25.                 {  
  26.                     throw ex;  
  27.                 }  
  28.                 return null;  
  29.             }  
  30.             return teams;  
  31.         }  
  32.         /// <summary>  
  33.         /// This method is created to get players list on the basis of team id.  
  34.         /// </summary>  
  35.         /// <param name="teamId"></param>  
  36.         /// <param name="page"></param>  
  37.         /// <param name="pageSize"></param>  
  38.         /// <returns></returns>  
  39.         public List<Players> GetPlayersByTeam(int teamId, string page, string pageSize)  
  40.         {  
  41.             List<Players> playersList = null;  
  42.             try  
  43.             {  
  44.                 playersList = new PlayersDAL().GetPlayersByTeam(teamId, page, pageSize);  
  45.             }  
  46.             catch (Exception ex)  
  47.             {  
  48.                 bool rethrow = false;  
  49.                 if (rethrow)  
  50.                 {  
  51.                     throw ex;  
  52.                 }  
  53.                 return null;  
  54.             }  
  55.             return playersList;  
  56.         }  
  57.     }  
  58. }  
Step 9
 
Now Build the project. Now, we will proceed with our user interface part.

Creating User Interface

In this section, we’ll get the data from “BestPlayers.Core” project with the help of the controllers and then we will pass binded view with the controller by the help of models. We will add the controllers, views and partial views to create the user interface. Thus, let’s begin with the steps given below.

Step 1

Just right click on the project and click Add Reference to add the reference of Core project. Just perform, as shown below.


Figure 9: Adding Core Project Reference

Step 2

Now, right click on the Controllers folder and go to Add-> Controller.


Figure 10: Adding Controller

Step 3

Select MVC Empty Controller from the next Add Scaffold wizard.


Figure 11: Add Scaffold Wizard

Step 4

Specify the controllers name as “PlayersController”. 


Figure 12: Add Controller

Step 5

Update the Model with the help of following code.
  1. using System.Collections.Generic;  
  2.   
  3. namespace BestPlayers.Core.Models  
  4. {  
  5.     public class Team  
  6.     {  
  7.         #region Properties  
  8.         /// <summary>  
  9.         /// get and set the ID  
  10.         /// </summary>  
  11.         public int ID { get; set; }  
  12.         /// <summary>  
  13.         /// get and set the Name  
  14.         /// </summary>  
  15.         public string Name { get; set; }  
  16.         #endregion  
  17.     }  
  18.   
  19.     public class Players  
  20.     {  
  21.         #region Properties  
  22.         /// <summary>  
  23.         /// get and set the ID  
  24.         /// </summary>  
  25.         public int ID { get; set; }  
  26.         /// <summary>  
  27.         /// get and set the Name  
  28.         /// </summary>  
  29.         public string Name { get; set; }  
  30.         /// <summary>  
  31.         /// get and set the ODI  
  32.         /// </summary>  
  33.         public int ODI { get; set; }  
  34.         /// <summary>  
  35.         /// get and set the Tests  
  36.         /// </summary>  
  37.         public int Tests { get; set; }  
  38.         /// <summary>  
  39.         /// get and set the ODIRuns  
  40.         /// </summary>  
  41.         public int ODIRuns { get; set; }  
  42.         /// <summary>  
  43.         /// get and set the TestRuns  
  44.         /// </summary>  
  45.         public int TestRuns { get; set; }  
  46.         /// <summary>  
  47.         /// get and set the TotalCount  
  48.         /// </summary>  
  49.         public int TotalCount { get; set; }  
  50.         #endregion  
  51.     }  
  52.   
  53.     public class Cricketer  
  54.     {  
  55.         #region Properties  
  56.         /// <summary>  
  57.         /// get and set the Teams  
  58.         /// </summary>  
  59.         public List<Team> Teams { get; set; }  
  60.         #endregion  
  61.     }  
  62. }  
Step 6

Now, replace the code with the code given below.
  1. using BestPlayers.Core.BL;  
  2. using BestPlayers.Core.Models;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace BestPlayers.Controllers  
  8. {  
  9.     public class PlayerController : Controller  
  10.     {  
  11.         #region Cricketer          
  12.         /// <summary>    
  13.         /// This method is used to get all cricketer names    
  14.         /// </summary>    
  15.         /// <returns></returns>    
  16.         [HttpGet, ActionName("GetAllTeams")]  
  17.         public ActionResult GetAllTeams()  
  18.         {  
  19.             List<Team> teamList = new List<Team>();  
  20.   
  21.             var response = new PlayersBL().GetAllTeams();  
  22.             if (!object.Equals(response, null))  
  23.             {  
  24.                 teamList = response.ToList();  
  25.             }  
  26.             return View("~/Views/Player/Teams.cshtml"new Cricketer { Teams = teamList });  
  27.         }  
  28.         #endregion  
  29.     }  
  30. }  
Step 7

Now, right click on the Players folder in the Views folder and go to Add-> View.


Figure 13: Adding View

Step 8

Specify the name for view as “Teams”, as shown below.


Figure 14: View in MVC

Step 9

Now, replace the code with the code given below.
  1. @model BestPlayers.Core.Models.Cricketer  
  2. @{  
  3.     ViewBag.Title = "Teams";  
  4.  
  5.   
  6. <h2>Teams</h2>  
  7.   
  8. <table>  
  9.     <thead>  
  10.         <tr>  
  11.             <th>  
  12.                 Name  
  13.             </th>  
  14.         </tr>  
  15.     </thead>  
  16.     <tbody>  
  17.         @if (Model.Teams.Count > 0)  
  18.         {  
  19.             foreach (var item in Model.Teams)  
  20.             {  
  21.                 <tr>  
  22.                     <td>  
  23.                         <a href="javascript:void(0)" onclick="GetPlayersDetails('@item.ID')">@item.Name</a>  
  24.                     </td>  
  25.                 </tr>  
  26.             }  
  27.         }  
  28.     </tbody>  
  29. </table>  
Step 10

Add the connection string given below in the Web.Config file of MVC project.
  1. <add name="PlayersConfiguration" connectionString="Data Source=Your Server Name; Initial Catalog=Cricketer; User Id=User Name; Password=Password" providerName="System.Data.SqlClient"/>  
Step 11

Modify the code in the “Views/Shared/_Layout.cshtml” with the highlighted code given 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 - Best Players App</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("Best Players""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("Cricket""GetAllTeams""Player")</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 - Best Players App</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 12

Run the Application with Ctrl + F5. Click the Cricketer link.


Figure 15: Dashborad in MVC

Now, you can see that all the teams are listed below.


Figure 16: Team View in MVC

Binding Partial View with jQuery Dialog

In this section, we’ll add one partial view and render the partial view in a div element with the help of jQuery Dialog. We’ll set the datatype as HTML in jQuery function to render the partial view. Let’s begin with the steps given below.

Step 1

Right click on the Views-> Player folder and go to Add -> View.


Figure 17: Adding Partial View

Step 2

Check the option of creating Partial View in the wizard, as shown below.


Figure 18: Partial View in MVC

Step 3

At first, we’ll add the PagedList reference in our Application. In the Solution Explorer, right click on the BestPlayers and go to Manage NuGet Packages and search for the PagedList. Subsequently, install it as shown below.


Figure 19: Adding PagedList Reference

Step 4

Now, add an action method in the PlayersController with the help of the code given below.

At first, add the reference given below.
  1. using PagedList;  
Now, add the code in the PlayersController, as defined below.
  1. /// <summary>  
  2. /// This method is created to get all players on the basis of team id.  
  3. /// </summary>  
  4. /// <param name="page"></param>  
  5. /// <param name="pageSize"></param>  
  6. /// <param name="teamId"></param>  
  7. /// <returns></returns>  
  8. [HttpGet, ActionName("GetPlayersByTeam")]  
  9. public ActionResult GetPlayersByTeam(int? page, int? pageSize, int teamId)  
  10. {  
  11.     List<Players> playersList = new List<Players>();  
  12.     if (object.Equals(page, null))  
  13.     {  
  14.         page = 1;  
  15.     }  
  16.     if (object.Equals(pageSize, null))  
  17.     {  
  18.         pageSize = 4;  
  19.     }  
  20.     ViewBag.TeamId = teamId;  
  21.     ViewBag.PageSize = pageSize;  
  22.     var response = new PlayersBL().GetPlayersByTeam(teamId, page.ToString(), pageSize.ToString());  
  23.     if (!object.Equals(response, null))  
  24.     {  
  25.         playersList = response.ToList();  
  26.     }  
  27.   
  28.     return View("~/Views/Player/_PlayerPartial.cshtml"new StaticPagedList<Players>(playersList, Convert.ToInt32(page), Convert.ToInt32(pageSize), playersList.Count > 0 ? playersList.FirstOrDefault().TotalCount : 0));  
  29. }  
Step 5

Add jQuery & jQueryUI reference and unobtrusive reference from the NuGet Packages.


Figure 20: Adding jQuery Reference

Step 6

Add the highlighted code given below in Team.cshtml page.
  1. @model BestPlayers.Core.Models.Cricketer  
  2. @{  
  3.     ViewBag.Title = "Teams";  
  4. }  
  5. <script src="~/Scripts/jquery-2.1.1.js"></script>  
  6. <script src="~/Scripts/jquery-ui-1.11.1.js"></script>  
  7. <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>  
  8. <link href="~/Content/themes/base/jquery-ui.min.css" rel="stylesheet" />  
  9.   
  10. <h2>Teams</h2>  
  11.   
  12. <table>  
  13.     <thead>  
  14.         <tr>  
  15.             <th>  
  16.                 Name  
  17.             </th>  
  18.         </tr>  
  19.     </thead>  
  20.     <tbody>  
  21.         @if (Model.Teams.Count > 0)  
  22.         {  
  23.             foreach (var item in Model.Teams)  
  24.             {  
  25.                 <tr>  
  26.                     <td>  
  27.                         <a href="javascript:void(0)" onclick="GetPlayersDetails('@item.ID')">@item.Name</a>  
  28.                     </td>  
  29.                 </tr>  
  30.             }  
  31.         }  
  32.     </tbody>  
  33. </table>  
  34.   
  35. <div class="popupcntr" id="playerDetails_content" style="display: none;" title="Event Information">  
  36.     <div class="innerBox">  
  37.         <div id="PlayerContainer"></div>  
  38.     </div>  
  39. </div>  
  40.   
  41. <script type="text/javascript">  
  42.     var j$ = jQuery.noConflict();  
  43.     function GetPlayersDetails(teamId) {  
  44.         j$(function () {  
  45.             j$('#playerDetails_content').dialog({  
  46.                 dialogClass: 'eventdetail_dialog',  
  47.                 modal: true,  
  48.                 width: 676,  
  49.                 open: function (event, ui) {  
  50.                     $.ajax({  
  51.                         url: '@Url.Action("GetPlayersByTeam", "Player")'//"/Player/GetPlayersByTeam",  
  52.                         dataType: "html",  
  53.                         data: { teamId: teamId },  
  54.                         type: "GET",  
  55.                         error: function (xhr, status, error) {  
  56.                             var err = eval("(" + xhr.responseText + ")");  
  57.                             toastr.error(err.message);  
  58.                         },  
  59.                         success: function (data) {  
  60.                             $('#PlayerContainer').html(data);  
  61.                         }  
  62.                     });  
  63.                 },  
  64.                 close: function (event, ui) { $('#playerDetails_content').dialog("destroy"); $('#PlayerContainer').html(""); },  
  65.             });  
  66.         });  
  67.     }  
  68. </script>  
Step 7

Replace the code of _PlayerPartial.cshtml page with the code given below.
  1. @model PagedList.IPagedList<BestPlayers.Core.Models.Players>  
  2. @using PagedList.Mvc;  
  3.   
  4. <table class="table">  
  5.     <thead>  
  6.         <tr>  
  7.             <th>  
  8.                 Name  
  9.             </th>  
  10.             <th>  
  11.                 ODI  
  12.             </th>  
  13.             <th>  
  14.                 Tests  
  15.             </th>  
  16.             <th>  
  17.                 ODIRuns  
  18.             </th>  
  19.             <th>  
  20.                 TestRuns  
  21.             </th>  
  22.         </tr>  
  23.     </thead>  
  24.     <tbody>  
  25.         @if (Model.Count > 0)  
  26.         {  
  27.             foreach (var item in Model)  
  28.             {  
  29.                 <tr>  
  30.                     <td>  
  31.                         @item.Name  
  32.                     </td>  
  33.                     <td>  
  34.                         @item.ODI  
  35.                     </td>  
  36.                     <td>  
  37.                         @item.Tests  
  38.                     </td>  
  39.                     <td>  
  40.                         @item.ODIRuns  
  41.                     </td>  
  42.                     <td>  
  43.                         @item.TestRuns  
  44.                     </td>  
  45.                 </tr>  
  46.             }  
  47.         }  
  48.         else  
  49.         {  
  50.             <tr>  
  51.                 <td colspan="13" class="NoData">No data found</td>  
  52.             </tr>  
  53.         }  
  54.     </tbody>  
  55. </table>  
  56. @if (Model.TotalItemCount > 4)  
  57. {  
  58.     <div class="pagingBox">  
  59.         <input id="HiddenPageSize" name="PageSize" type="hidden" />  
  60.         <input id="HiddenPage" name="Page" type="hidden" />  
  61.         <span class="selectBoxes display_none_mobile">  
  62.             @Html.DropDownList("PageSize"new SelectList(new Dictionary<string, int> { { "2", 2 }, { "4", 4 } }, "Key""Value", Convert.ToString(ViewBag.PageSize)), new { id = "pagesizelist" })  
  63.         </span>  
  64.         <div class="pagerecord display_none_mobile">  
  65.             Records  
  66.   
  67.             Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumberof @Model.PageCount  
  68.         </div>  
  69.   
  70.         @Html.PagedListPager(Model, page => Url.Action("GetPlayersByTeam""Player",  
  71.                                       new  
  72.                                       {  
  73.                                           page,  
  74.                                           pageSize = ViewBag.PageSize,  
  75.                                           teamId = ViewBag.TeamId  
  76.                                       }),  
  77.                                    PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions  
  78.                                     {  
  79.                                         Display = PagedListDisplayMode.IfNeeded,  
  80.                                         MaximumPageNumbersToDisplay = 5  
  81.                                     },  
  82.                                    new AjaxOptions  
  83.                                    {  
  84.                                        InsertionMode = InsertionMode.Replace,  
  85.                                        HttpMethod = "Get",  
  86.                                        UpdateTargetId = "PlayerContainer"  
  87.                                    }))  
  88.     </div>  
  89. }  
  90. <script type="text/javascript">  
  91.     //This mehtod is used to call when Page Size list is changed  
  92.     $(function () {  
  93.         $("#pagesizelist").change(function (event) {  
  94.             $.ajax({  
  95.                 url: '@Url.Action("GetPlayersByTeam", "Player")'//"/Player/GetPlayersByTeam",  
  96.                 dataType: "html",  
  97.                 data: {  
  98.                     page: 1,  
  99.                     pageSize: $(this).val(),  
  100.                     teamId: '@ViewBag.TeamId'  
  101.                 },  
  102.                 type: "GET",  
  103.                 error: function (xhr, status, error) {  
  104.                     var err = eval("(" + xhr.responseText + ")");  
  105.                     toastr.error(err.message);  
  106.                 },  
  107.                 success: function (data) {                      
  108.                     $('#PlayerContainer').html(data);  
  109.                 }  
  110.             });  
  111.         });  
  112.     });  
  113. </script>  
Step 8

Build the Application and run the Application. Open the Cricketer page and click India.


Figure 21: Cricketer View in App

Step 9

When you click on India, you will get the details of the players listed in Indian team.


Figure 22: Partial View with jQuery Dialog

You can also perform paging in this dialog box.


Figure 23: Paging in Partial View with jQuery Dialog

Note - The records are available only for India. One can easily insert the data into the table to get more records.

Summary

This article described how we can integrate the partial view with div element, with the help of jQuery & jQuery UI. This is one of the benefits of using partial view in any ASP.NET MVC application. We also saw the easy paging functionality and no postback while paging in this application. Thanks for reading this article. Happy coding.

Up Next
    Ebook Download
    View all
    Learn
    View all