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.

So, let’s start with the following procedure,

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. SET ANSI_NULLS ON
  4. GO
  5. SET QUOTED_IDENTIFIER ON
  6. GO
  7. SET ANSI_PADDING ON
  8. GO
  9. CREATE TABLE [dbo].[CricketerProfile](
  10. [ID] [int] IDENTITY(1,1) NOT NULL,
  11. [Name] [varchar](50) NULL,
  12. [ODI] [int] NULL,
  13. [Tests] [int] NULL,
  14. [ODIRuns] [int] NULL,
  15. [TestRuns] [int] NULL,
  16. [Team] [int] NULL,
  17. CONSTRAINT [PK_CricketerProfile] PRIMARY KEY CLUSTERED
  18. (
  19. [ID] ASC
  20. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  21. ) ON [PRIMARY]
  22. GO
  23. SET ANSI_PADDING OFF
  24. GO
  25. SET ANSI_NULLS ON
  26. GO
  27. SET QUOTED_IDENTIFIER ON
  28. GO
  29. SET ANSI_PADDING ON
  30. GO
  31. CREATE TABLE [dbo].[Team](
  32. [ID] [int] IDENTITY(1,1) NOT NULL,
  33. [Name] [varchar](50) NULL,
  34. PRIMARY KEY CLUSTERED
  35. (
  36. [ID] ASC
  37. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
  38. ) ON [PRIMARY]
  39. GO
  40. SET ANSI_PADDING OFF
  41. GO
  42. SET IDENTITY_INSERT [dbo].[CricketerProfile] ON
  43. GO
  44. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (1, N'Sachin Tendulkar', 463, 200, 18426, 15921, 1)
  45. GO
  46. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (2, N'Saurav Ganguly', 311, 113, 11363, 7212, 1)
  47. GO
  48. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (3, N'Rahul Dravid', 344, 164, 10889, 13228, 1)
  49. GO
  50. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (4, N'V.V.S. Laxman', 86, 134, 2338, 8781, 1)
  51. GO
  52. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (5, N'Virendar Sehwag', 251, 104, 8273, 8586, 1)
  53. GO
  54. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (6, N'Yuvraj Singh', 293, 40, 8329, 1900, 1)
  55. GO
  56. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (7, N'M. S. Dhoni', 283, 90, 9110, 4876, 1)
  57. GO
  58. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (8, N'Virat Kohli', 176, 53, 7570, 4209, 1)
  59. GO
  60. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (9, N'Harbhajan Singh', 236, 103, 1237, 2225, 1)
  61. GO
  62. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (10, N'Anil Kumble', 271, 132, 938, 2506, 1)
  63. GO
  64. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (11, N'Gautam Gambhir', 147, 58, 5238, 4154, 1)
  65. GO
  66. INSERT [dbo].[CricketerProfile] ([ID], [Name], [ODI], [Tests], [ODIRuns], [TestRuns], [Team]) VALUES (12, N'Rohit Sharma', 153, 21, 5131, 1184, 1)
  67. GO
  68. SET IDENTITY_INSERT [dbo].[CricketerProfile] OFF
  69. GO
  70. SET IDENTITY_INSERT [dbo].[Team] ON
  71. GO
  72. INSERT [dbo].[Team] ([ID], [Name]) VALUES (1, N'India')
  73. GO
  74. INSERT [dbo].[Team] ([ID], [Name]) VALUES (2, N'Australia')
  75. GO
  76. INSERT [dbo].[Team] ([ID], [Name]) VALUES (3, N'New Zeland')
  77. GO
  78. INSERT [dbo].[Team] ([ID], [Name]) VALUES (4, N'South Africa')
  79. GO
  80. INSERT [dbo].[Team] ([ID], [Name]) VALUES (5, N'West Indies')
  81. GO
  82. SET IDENTITY_INSERT [dbo].[Team] OFF
  83. GO
  84. SET ANSI_NULLS ON
  85. GO
  86. SET QUOTED_IDENTIFIER ON
  87. GO
  88. CREATE Proc [dbo].[BP_GetAllTeams]
  89. AS
  90. Begin
  91. select * from Team (NOLOCK)
  92. End
  93. GO
  94. SET ANSI_NULLS ON
  95. GO
  96. SET QUOTED_IDENTIFIER ON
  97. GO
  98. --EXEC [BP_GetPlayersByTeam] 1, 1 , 4
  99. CREATE PROC [dbo].[BP_GetPlayersByTeam]
  100. @TeamId INT ,
  101. @PageNumber INT ,
  102. @PageSize INT
  103. AS
  104. BEGIN
  105. ;
  106. WITH PlayerCte
  107. AS ( SELECT ID ,
  108. Name ,
  109. ODI ,
  110. Tests ,
  111. ODIRuns ,
  112. TestRuns
  113. FROM dbo.CricketerProfile (NOLOCK)
  114. WHERE Team = @TeamId
  115. )
  116. SELECT * ,
  117. ( SELECT COUNT(*)
  118. FROM PlayerCte
  119. )AS TotalCount
  120. FROM PlayerCte
  121. ORDER BY PlayerCte.ID
  122. OFFSET @PageSize * ( @PageNumber - 1 ) ROWS
  123. FETCH NEXT @PageSize ROWS ONLY
  124. OPTION ( RECOMPILE );
  125. END;
  126. 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. public class Players
  17. {
  18. #region Properties
  19. /// <summary>
  20. /// get and set the ID
  21. /// </summary>
  22. public int ID { get; set; }
  23. /// <summary>
  24. /// get and set the Name
  25. /// </summary>
  26. public string Name { get; set; }
  27. /// <summary>
  28. /// get and set the ODI
  29. /// </summary>
  30. public int ODI { get; set; }
  31. /// <summary>
  32. /// get and set the Tests
  33. /// </summary>
  34. public int Tests { get; set; }
  35. /// <summary>
  36. /// get and set the ODIRuns
  37. /// </summary>
  38. public int ODIRuns { get; set; }
  39. /// <summary>
  40. /// get and set the TestRuns
  41. /// </summary>
  42. public int TestRuns { get; set; }
  43. #endregion
  44. }
  45. }
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. namespace BestPlayers.Core.DAL
  12. {
  13. public class PlayersDAL
  14. {
  15. #region Variable
  16. /// <summary>
  17. /// variable for Database
  18. /// </summary>
  19. Database objDB;
  20. #endregion
  21. #region Database Method
  22. public List<T> ConvertTo<T>(DataTable datatable) where T : new()
  23. {
  24. List<T> Temp = new List<T>();
  25. try
  26. {
  27. List<string> columnsNames = new List<string>();
  28. foreach (DataColumn DataColumn in datatable.Columns)
  29. columnsNames.Add(DataColumn.ColumnName);
  30. Temp = datatable.AsEnumerable().ToList().ConvertAll<T>(row => getObject<T>(row, columnsNames));
  31. return Temp;
  32. }
  33. catch
  34. {
  35. return Temp;
  36. }
  37. }
  38. public T getObject<T>(DataRow row, List<string> columnsName) where T : new()
  39. {
  40. T obj = new T();
  41. try
  42. {
  43. string columnname = "";
  44. string value = "";
  45. PropertyInfo[] Properties;
  46. Properties = typeof(T).GetProperties();
  47. foreach (PropertyInfo objProperty in Properties)
  48. {
  49. columnname = columnsName.Find(name => name.ToLower() == objProperty.Name.ToLower());
  50. if (!string.IsNullOrEmpty(columnname))
  51. {
  52. value = row[columnname].ToString();
  53. if (!string.IsNullOrEmpty(value))
  54. {
  55. if (Nullable.GetUnderlyingType(objProperty.PropertyType) != null)
  56. {
  57. value = row[columnname].ToString().Replace("$", "").Replace(",", "");
  58. objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(Nullable.GetUnderlyingType(objProperty.PropertyType).ToString())), null);
  59. }
  60. else
  61. {
  62. value = row[columnname].ToString();
  63. objProperty.SetValue(obj, Convert.ChangeType(value, Type.GetType(objProperty.PropertyType.ToString())), null);
  64. }
  65. }
  66. }
  67. }
  68. return obj;
  69. }
  70. catch
  71. {
  72. return obj;
  73. }
  74. }
  75. #endregion
  76. /// <summary>
  77. /// This method is created to get all teams.
  78. /// </summary>
  79. /// <returns></returns>
  80. public List<Team> GetAllTeams()
  81. {
  82. List<Team> teams = new List<Team>();
  83. objDB = new SqlDatabase(ConfigurationManager.ConnectionStrings["PlayersConfiguration"].ConnectionString);
  84. using (DbCommand objCMD = objDB.GetStoredProcCommand("BP_GetAllTeams"))
  85. {
  86. try
  87. {
  88. using (DataTable dataTable = objDB.ExecuteDataSet(objCMD).Tables[0])
  89. {
  90. teams = ConvertTo<Team>(dataTable);
  91. }
  92. }
  93. catch (Exception ex)
  94. {
  95. bool rethrow = false;
  96. if (rethrow)
  97. {
  98. throw ex;
  99. }
  100. return null;
  101. }
  102. }
  103. return teams;
  104. }
  105. /// <summary>
  106. /// This method is created to get players list on the basis of team id.
  107. /// </summary>
  108. /// <param name="TeamId"></param>
  109. /// <param name="page"></param>
  110. /// <param name="pageSize"></param>
  111. /// <returns></returns>
  112. public List<Players> GetPlayersByTeam(int TeamId, string page, string pageSize)
  113. {
  114. List<Players> players = null;
  115. objDB = new SqlDatabase(ConfigurationManager.ConnectionStrings["PlayersConfiguration"].ConnectionString);
  116. using (DbCommand objCMD = objDB.GetStoredProcCommand("BP_GetPlayersByTeam"))
  117. {
  118. try
  119. {
  120. objDB.AddInParameter(objCMD, "@TeamId", DbType.Int32, TeamId);
  121. objDB.AddInParameter(objCMD, "@PageNumber", DbType.Int32, Convert.ToInt32(page));
  122. objDB.AddInParameter(objCMD, "@PageSize", DbType.Int32, Convert.ToInt32(pageSize));
  123. using (DataTable dataTable = objDB.ExecuteDataSet(objCMD).Tables[0])
  124. {
  125. players = ConvertTo<Players>(dataTable);
  126. }
  127. }
  128. catch (Exception ex)
  129. {
  130. bool rethrow = false;
  131. if (rethrow)
  132. {
  133. throw ex;
  134. }
  135. return null;
  136. }
  137. }
  138. return players;
  139. }
  140. }
  141. }
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. namespace BestPlayers.Core.BL
  6. {
  7. public class PlayersBL
  8. {
  9. /// <summary>
  10. /// This method is created to get all teams.
  11. /// </summary>
  12. /// <returns></returns>
  13. public List<Team> GetAllTeams()
  14. {
  15. List<Team> teams = null;
  16. try
  17. {
  18. teams = new PlayersDAL().GetAllTeams();
  19. }
  20. catch (Exception ex)
  21. {
  22. bool rethrow = false;
  23. if (rethrow)
  24. {
  25. throw ex;
  26. }
  27. return null;
  28. }
  29. return teams;
  30. }
  31. /// <summary>
  32. /// This method is created to get players list on the basis of team id.
  33. /// </summary>
  34. /// <param name="teamId"></param>
  35. /// <param name="page"></param>
  36. /// <param name="pageSize"></param>
  37. /// <returns></returns>
  38. public List<Players> GetPlayersByTeam(int teamId, string page, string pageSize)
  39. {
  40. List<Players> playersList = null;
  41. try
  42. {
  43. playersList = new PlayersDAL().GetPlayersByTeam(teamId, page, pageSize);
  44. }
  45. catch (Exception ex)
  46. {
  47. bool rethrow = false;
  48. if (rethrow)
  49. {
  50. throw ex;
  51. }
  52. return null;
  53. }
  54. return playersList;
  55. }
  56. }
  57. }
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. namespace BestPlayers.Core.Models
  3. {
  4. public class Team
  5. {
  6. #region Properties
  7. /// <summary>
  8. /// get and set the ID
  9. /// </summary>
  10. public int ID { get; set; }
  11. /// <summary>
  12. /// get and set the Name
  13. /// </summary>
  14. public string Name { get; set; }
  15. #endregion
  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. /// <summary>
  45. /// get and set the TotalCount
  46. /// </summary>
  47. public int TotalCount { get; set; }
  48. #endregion
  49. }
  50. public class Cricketer
  51. {
  52. #region Properties
  53. /// <summary>
  54. /// get and set the Teams
  55. /// </summary>
  56. public List<Team> Teams { get; set; }
  57. #endregion
  58. }
  59. }
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. namespace BestPlayers.Controllers
  7. {
  8. public class PlayerController : Controller
  9. {
  10. #region Cricketer
  11. /// <summary>
  12. /// This method is used to get all cricketer names
  13. /// </summary>
  14. /// <returns></returns>
  15. [HttpGet, ActionName("GetAllTeams")]
  16. public ActionResult GetAllTeams()
  17. {
  18. List<Team> teamList = new List<Team>();
  19. var response = new PlayersBL().GetAllTeams();
  20. if (!object.Equals(response, null))
  21. {
  22. teamList = response.ToList();
  23. }
  24. return View("~/Views/Player/Teams.cshtml", new Cricketer { Teams = teamList });
  25. }
  26. #endregion
  27. }
  28. }
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. <h2>Teams</h2>
  6. <table>
  7. <thead>
  8. <tr>
  9. <th>
  10. Name
  11. </th>
  12. </tr>
  13. </thead>
  14. <tbody>
  15. @if (Model.Teams.Count > 0)
  16. {
  17. foreach (var item in Model.Teams)
  18. {
  19. <tr>
  20. <td>
  21. <a href="javascript:void(0)" onclick="GetPlayersDetails('@item.ID')">@item.Name</a>
  22. </td>
  23. </tr>
  24. }
  25. }
  26. </tbody>
  27. </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. </head>
  10. <body>
  11. <div class="navbar navbar-inverse navbar-fixed-top">
  12. <div class="container">
  13. <div class="navbar-header">
  14. <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
  15. <span class="icon-bar"></span>
  16. <span class="icon-bar"></span>
  17. <span class="icon-bar"></span>
  18. </button>
  19. @Html.ActionLink("Best Players", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
  20. </div>
  21. <div class="navbar-collapse collapse">
  22. <ul class="nav navbar-nav">
  23. <li>@Html.ActionLink("Home", "Index", "Home")</li>
  24. <li>@Html.ActionLink("About", "About", "Home")</li>
  25. <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
  26. <li>@Html.ActionLink("Cricket", "GetAllTeams", "Player")</li>
  27. </ul>
  28. @Html.Partial("_LoginPartial")
  29. </div>
  30. </div>
  31. </div>
  32. <div class="container body-content">
  33. @RenderBody()
  34. <hr />
  35. <footer>
  36. <p>© @DateTime.Now.Year - Best Players App</p>
  37. </footer>
  38. </div>
  39. @Scripts.Render("~/bundles/jquery")
  40. @Scripts.Render("~/bundles/bootstrap")
  41. @RenderSection("scripts", required: false)
  42. </body>
  43. </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. return View("~/Views/Player/_PlayerPartial.cshtml", new StaticPagedList<Players>(playersList, Convert.ToInt32(page), Convert.ToInt32(pageSize), playersList.Count > 0 ? playersList.FirstOrDefault().TotalCount : 0));
  28. }
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. <h2>Teams</h2>
  10. <table>
  11. <thead>
  12. <tr>
  13. <th>
  14. Name
  15. </th>
  16. </tr>
  17. </thead>
  18. <tbody>
  19. @if (Model.Teams.Count > 0)
  20. {
  21. foreach (var item in Model.Teams)
  22. {
  23. <tr>
  24. <td>
  25. <a href="javascript:void(0)" onclick="GetPlayersDetails('@item.ID')">@item.Name</a>
  26. </td>
  27. </tr>
  28. }
  29. }
  30. </tbody>
  31. </table>
  32. <div class="popupcntr" id="playerDetails_content" style="display: none;" title="Event Information">
  33. <div class="innerBox">
  34. <div id="PlayerContainer"></div>
  35. </div>
  36. </div>
  37. <script type="text/javascript">
  38. var j$ = jQuery.noConflict();
  39. function GetPlayersDetails(teamId) {
  40. j$(function () {
  41. j$('#playerDetails_content').dialog({
  42. dialogClass: 'eventdetail_dialog',
  43. modal: true,
  44. width: 676,
  45. open: function (event, ui) {
  46. $.ajax({
  47. url: '@Url.Action("GetPlayersByTeam", "Player")', //"/Player/GetPlayersByTeam",
  48. dataType: "html",
  49. data: { teamId: teamId },
  50. type: "GET",
  51. error: function (xhr, status, error) {
  52. var err = eval("(" + xhr.responseText + ")");
  53. toastr.error(err.message);
  54. },
  55. success: function (data) {
  56. $('#PlayerContainer').html(data);
  57. }
  58. });
  59. },
  60. close: function (event, ui) { $('#playerDetails_content').dialog("destroy"); $('#PlayerContainer').html(""); },
  61. });
  62. });
  63. }
  64. </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. <table class="table">
  4. <thead>
  5. <tr>
  6. <th>
  7. Name
  8. </th>
  9. <th>
  10. ODI
  11. </th>
  12. <th>
  13. Tests
  14. </th>
  15. <th>
  16. ODIRuns
  17. </th>
  18. <th>
  19. TestRuns
  20. </th>
  21. </tr>
  22. </thead>
  23. <tbody>
  24. @if (Model.Count > 0)
  25. {
  26. foreach (var item in Model)
  27. {
  28. <tr>
  29. <td>
  30. @item.Name
  31. </td>
  32. <td>
  33. @item.ODI
  34. </td>
  35. <td>
  36. @item.Tests
  37. </td>
  38. <td>
  39. @item.ODIRuns
  40. </td>
  41. <td>
  42. @item.TestRuns
  43. </td>
  44. </tr>
  45. }
  46. }
  47. else
  48. {
  49. <tr>
  50. <td colspan="13" class="NoData">No data found</td>
  51. </tr>
  52. }
  53. </tbody>
  54. </table>
  55. @if (Model.TotalItemCount > 4)
  56. {
  57. <div class="pagingBox">
  58. <input id="HiddenPageSize" name="PageSize" type="hidden" />
  59. <input id="HiddenPage" name="Page" type="hidden" />
  60. <span class="selectBoxes display_none_mobile">
  61. @Html.DropDownList("PageSize", new SelectList(new Dictionary<string, int> { { "2", 2 }, { "4", 4 } }, "Key", "Value", Convert.ToString(ViewBag.PageSize)), new { id = "pagesizelist" })
  62. </span>
  63. <div class="pagerecord display_none_mobile">
  64. Records
  65. Page @(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of @Model.PageCount
  66. </div>
  67. @Html.PagedListPager(Model, page => Url.Action("GetPlayersByTeam", "Player",
  68. new
  69. {
  70. page,
  71. pageSize = ViewBag.PageSize,
  72. teamId = ViewBag.TeamId
  73. }),
  74. PagedListRenderOptions.EnableUnobtrusiveAjaxReplacing(new PagedListRenderOptions
  75. {
  76. Display = PagedListDisplayMode.IfNeeded,
  77. MaximumPageNumbersToDisplay = 5
  78. },
  79. new AjaxOptions
  80. {
  81. InsertionMode = InsertionMode.Replace,
  82. HttpMethod = "Get",
  83. UpdateTargetId = "PlayerContainer"
  84. }))
  85. </div>
  86. }
  87. <script type="text/javascript">
  88. //This mehtod is used to call when Page Size list is changed
  89. $(function () {
  90. $("#pagesizelist").change(function (event) {
  91. $.ajax({
  92. url: '@Url.Action("GetPlayersByTeam", "Player")', //"/Player/GetPlayersByTeam",
  93. dataType: "html",
  94. data: {
  95. page: 1,
  96. pageSize: $(this).val(),
  97. teamId: '@ViewBag.TeamId'
  98. },
  99. type: "GET",
  100. error: function (xhr, status, error) {
  101. var err = eval("(" + xhr.responseText + ")");
  102. toastr.error(err.message);
  103. },
  104. success: function (data) {
  105. $('#PlayerContainer').html(data);
  106. }
  107. });
  108. });
  109. });
  110. </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.