Click here to Skip to main content
15,887,485 members
Articles / Web Development / HTML
Tip/Trick

How to use jQuery Grid with ASP.NET MVC

Rate me:
Please Sign up or sign in to vote.
4.74/5 (23 votes)
11 Apr 2015MIT3 min read 129.6K   7.8K   41   26
This tip presents a simple example on how to use jQuery Grid Plugin in ASP.NET MVC with bootstrap.

jQuery Grid by Gijgo.com

Introduction

This tip is going to show how you can easily implement paging, sorting, filtering and CRUD operations with jQuery Grid Plugin in ASP.NET MVC with bootstrap.

Background

In the sample project that you can download from this tip, I'm using jQuery Grid 0.4.3 by gijgo.com, jQuery 2.1.3, Bootstrap 3.3.4 and AspNet.Mvc 5.2.3.

A Few Words about jQuery Grid by gijgo.com

Since the other libraries that are in use are pretty popular compared to the grid plugin. I'm going to give you some information about this plugin.

  • Stylish and Featured Tabular data presentation control
  • JavaScript control for representing and manipulating tabular data on the web
  • Ajax enabled
  • Can be integrated with any of the server-side technologies like ASP, JavaServlets, JSP, PHP, etc
  • Very simple to integrate with ASP.NET
  • Support pagination, JavaScript and server side data sources
  • Support jQuery UI and Bootstrap
  • Free open source tool distributed under MIT License

You can find the documentation about the version of the plugin that is in use in this tip at http://gijgo.com/version_0_4/Documentation.

Integrating jQuery Grid with ASP.NET MVC - Step By Step

  • Create a new ASP.NET MVC project in Visual Studio.
  • I assume that jquery and bootstrap would be added to your ASP.NET MVC project by default. If they are not added, you can find and add them to your project via nuget.
  • Add jQuery Grid by gijgo.com via nuget. You can find more information at https://www.nuget.org/packages/jQuery.Grid/.
  • Make sure that you have a reference to jquery.js, bootstrap.css, grid.css and grid.js files in the pages where you are planning to use the jquery grid.

jQuery Grid References

In order to use the grid plugin, you will need a HTML table tag for a base element of the grid. I recommend to use the "data-source" attribute of the table as identification for the location of source url on the server side.

HTML
<table id="grid" data-source="@Url.Action("GetPlayers")"></table>

After that, we have to initialize the table as jquery grid with the fields which we are planning to display in the grid.

JavaScript
grid = $("#grid").grid({
  dataKey: "ID",
  uiLibrary: "bootstrap",
  columns: [
    { field: "ID", width: 50, sortable: true },
    { field: "Name", sortable: true },
    { field: "PlaceOfBirth", title: "Place Of Birth", sortable: true },
    { field: "DateOfBirth", title: "Date Of Birth", sortable: true },
    { field: "Edit", title: "", width: 34, type: "icon",
    icon: "glyphicon-pencil", tooltip: "Edit", events: { "click": Edit } },
    { field: "Delete", title: "", width: 34, type: "icon",
    icon: "glyphicon-remove", tooltip: "Delete", events: { "click": Remove } }
  ],
  pager: { enable: true, limit: 5, sizes: [2, 5, 10, 20] }
});

If you want to be able to sort by particular column, you need to set the sortable option of the column to true. When you do that, the grid plugin is going to send information to the server about the field name that needs to be sorted. In order to configure paging, you have to use the pager option from where you can control the paging.

In the sample project, I use the following code to implement simple CRUD operations over the data inside the grid.

JavaScript
function Add() {
  $("#playerId").val("");
  $("#name").val("");
  $("#placeOfBirth").val("");
  $("#dateOfBirth").val("");
  $("#playerModal").modal("show");
}
function Edit(e) {
  $("#playerId").val(e.data.id);
  $("#name").val(e.data.record.Name);
  $("#placeOfBirth").val(e.data.record.PlaceOfBirth);
  $("#dateOfBirth").val(e.data.record.DateOfBirth);
  $("#playerModal").modal("show");
}
function Save() {
  var player = {
    ID: $("#playerId").val(),
    Name: $("#name").val(),
    PlaceOfBirth: $("#placeOfBirth").val(),
    DateOfBirth: $("#dateOfBirth").val()
  };
  $.ajax({ url: "Home/Save", type: "POST", data: { player: player } })
    .done(function () {
      grid.reload();
      $("#playerModal").modal("hide");
    })
    .fail(function () {
      alert("Unable to save.");
      $("#playerModal").modal("hide");
    });
}
function Remove(e) {
  $.ajax({ url: "Home/Remove", type: "POST", data: { id: e.data.id } })
    .done(function () {
      grid.reload();
    })
    .fail(function () {
      alert("Unable to remove.");
    });
}
function Search() {
  grid.reload({ searchString: $("#search").val() });
}

Server Side

In the Controller, we need only 4 methods, Index, GetPlayers, Save and Remove.

C#
[NoCache]
public class HomeController : Controller
{
  public ActionResult Index()
  {
    return View();
  }

  [HttpGet]
  public JsonResult GetPlayers(int? page, int? limit,
  string sortBy, string direction, string searchString = null)
  {
    int total;
    var records = new GridModel().GetPlayers
    (page, limit, sortBy, direction, searchString, out total);
    return Json(new { records, total }, JsonRequestBehavior.AllowGet);
  }

  [HttpPost]
  public JsonResult Save(Player player)
  {
    new GridModel().Save(player);
    return Json(true);
  }

  [HttpPost]
  public JsonResult Remove(int id)
  {
    new GridModel().Remove(id);
    return Json(true);
  }
}

Please note that I'm using custom "[NoCache]" attribute for the controller, that is going to resolve some issues with the caching. I recommend the usage of such attribute or similar mechanism for prevention of bugs related to caching.

C#
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public sealed class NoCacheAttribute : ActionFilterAttribute
{
  public override void OnResultExecuting(ResultExecutingContext filterContext)
  {
    filterContext.HttpContext.Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
    filterContext.HttpContext.Response.Cache.SetValidUntilExpires(false);
    filterContext.HttpContext.Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
    filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
    filterContext.HttpContext.Response.Cache.SetNoStore();
    base.OnResultExecuting(filterContext);
  }
}

In the data model of this example, I use XML as data store in order to simplify the logic in the model. You can customize the data model as you want and replace my implementation with code that is using relational databases like Microsoft SQL Server, My SQL or other services that are specific for your project.

I hope that this tip is going to be useful for your project. Happy coding!

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Architect
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionError with running solution Pin
Hasan AYDOS TURKEY14-Jul-17 4:57
Hasan AYDOS TURKEY14-Jul-17 4:57 
QuestionPlease suggest me how to implement for some of the enhancements Pin
User 558410213-Aug-16 3:58
User 558410213-Aug-16 3:58 
AnswerRe: Please suggest me how to implement for some of the enhancements Pin
Atanas N Atanasov15-Aug-16 20:28
Atanas N Atanasov15-Aug-16 20:28 
GeneralRe: Please suggest me how to implement for some of the enhancements Pin
User 558410216-Aug-16 2:04
User 558410216-Aug-16 2:04 
QuestionIs this using Entity Framework Pin
Member 1179939215-Jun-16 5:48
Member 1179939215-Jun-16 5:48 
AnswerRe: Is this using Entity Framework Pin
Atanas N Atanasov28-Jun-16 22:06
Atanas N Atanasov28-Jun-16 22:06 
QuestionConflict in pager when I have two grids in same page Pin
sumit703429-May-16 19:21
sumit703429-May-16 19:21 
AnswerRe: Conflict in pager when I have two grids in same page Pin
Atanas N Atanasov31-May-16 20:00
Atanas N Atanasov31-May-16 20:00 
Questionpassing parameters to the jquery grid on bind Pin
Brad100013-Apr-16 4:03
Brad100013-Apr-16 4:03 
AnswerRe: passing parameters to the jquery grid on bind Pin
Atanas N Atanasov31-May-16 21:26
Atanas N Atanasov31-May-16 21:26 
QuestionWhere's icons image? Pin
hugo.ayala6925-Feb-16 5:40
hugo.ayala6925-Feb-16 5:40 
AnswerRe: Where's icons image? Pin
Atanas N Atanasov31-May-16 20:02
Atanas N Atanasov31-May-16 20:02 
QuestionComplex types Pin
Member 1226440710-Feb-16 15:34
Member 1226440710-Feb-16 15:34 
AnswerRe: Complex types Pin
Atanas N Atanasov31-May-16 21:24
Atanas N Atanasov31-May-16 21:24 
QuestionPostback functions not working Pin
JimFeng3-Feb-16 6:29
JimFeng3-Feb-16 6:29 
QuestionComplex Type Pin
jrkblo19-Oct-15 2:05
jrkblo19-Oct-15 2:05 
AnswerRe: Complex Type Pin
Atanas N Atanasov19-Oct-15 20:19
Atanas N Atanasov19-Oct-15 20:19 
QuestionJson.parse unexpected end of data at line 1 character 1 Pin
vikramp6-Oct-15 5:54
vikramp6-Oct-15 5:54 
AnswerRe: Json.parse unexpected end of data at line 1 character 1 Pin
Atanas N Atanasov6-Oct-15 21:27
Atanas N Atanasov6-Oct-15 21:27 
GeneralRe: Json.parse unexpected end of data at line 1 character 1 Pin
vikramp7-Oct-15 3:45
vikramp7-Oct-15 3:45 
Questionhow to do case insensitive and wildcard search? Pin
Member 93308502-Jun-15 4:52
Member 93308502-Jun-15 4:52 
AnswerRe: how to do case insensitive and wildcard search? Pin
Atanas N Atanasov3-Jun-15 20:50
Atanas N Atanasov3-Jun-15 20:50 
QuestionGreat Demo Pin
ksafford17-Apr-15 8:04
ksafford17-Apr-15 8:04 
AnswerRe: Great Demo Pin
Atanas N Atanasov18-Apr-15 5:01
Atanas N Atanasov18-Apr-15 5:01 
GeneralMy vote of 5 Pin
Camilo Reyes13-Apr-15 5:05
professionalCamilo Reyes13-Apr-15 5:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.