Click here to Skip to main content
15,867,594 members
Articles / Web Development / HTML

ASP.NET MVC HTML Helper for the jqGrid

Rate me:
Please Sign up or sign in to vote.
4.91/5 (21 votes)
14 Jul 2014CPOL3 min read 202.6K   12.8K   77   55
The MvcJqGrid is an HTML helper that eases greatly the implementation of the jqGrid in MVC 3 with the Razor view engine or MVC WebForms.

Introduction

The jqGrid is a great grid with a lot of features, but the free version must be developed using JavaScript. If you are developing in MVC, having a free Html Helper would be great. This is where the MvcJqGrid enters.

The MvcJqGrid is an HTML helper that eases greatly the implementation of the jqGrid in MVC 3 with the Razor view engine or MVC WebForms.  

The  MvcJqGrid is available on the nuget gallery and can be installed on your project using the Package Manager Console:

PM> Install-Package MvcJqGrid

It can also be added to your project using the visual studio right-click on the References node and selecting Manage NuGet Packages. See Managing NuGet Packages Using the Dialog for more information.

To use the MvcJqGrid include the namespace in the view.

C#
@using MvcJqGrid

or the web.config in the namespaces of the system.web.webPages.razor section.

A simple example:

C#
@(Html.Grid("CustomerGrid")
    .SetCaption("Customers")
    .AddColumn(new Column("CustomerId").SetLabel("Id"))
    .AddColumn(new Column("Name"))
    .AddColumn(new Column("Company"))
    .SetUrl(Url.Action("List","Customer"))
    .SetAutoWidth(true)
    .SetRowNum(10)
    .SetViewRecords(true)
    .SetPager("pager"))

The HTML is self explanatory:

  • Html.Grid("CustomerGrid") - Creates the grid with id CustomerGrid
  • SetCaption - Sets the grid caption
  • AddColumn - Adds the columns to the grid
  • SetUrl - The Action and Controller that returns the json formatted for the jqGrid 
  • SetLabel - Sets the Label of the column that appears in the grid

A simple MVC controller for the grid is:

C#
public ActionResult List(GridSettings gridSettings)
{
   CustomerRepository repository = new CustomerRepository();
   string name = string.Empty;
   string company = string.Empty;
            
   if (gridSettings.IsSearch)
   {
       name = gridSettings.Where.rules.Any(r => r.field == "Name") ? 
              gridSettings.Where.rules.FirstOrDefault(r => r.field == "Name").data : string.Empty;
       company = gridSettings.Where.rules.Any(r => r.field == "Company") ? 
       gridSettings.Where.rules.FirstOrDefault(r => r.field == "Company").data : string.Empty;
   }

   var customers = repository.List(name, company, gridSettings.SortColumn, gridSettings.SortOrder);
   int totalCustomers = customers.Count;
   var jsonData = new
   {
        total = totalCustomers / gridSettings.PageSize + 1,
        page = gridSettings.PageIndex,
        records = totalCustomers,
        rows = (
                from c in customers
                select new
                {
                    id = c.CustomerID,
                    cell = new[]
                    {
                        c.CustomerID.ToString(),
                        string.Format("{0} {1}", c.FirstName, c.LastName),
                        c.CompanyName,
                        c.EmailAddress
                    }
        }).ToArray()
    };

    return Json(jsonData, JsonRequestBehavior.AllowGet);
}

A more complex example, with a column for operations like edit and delete is:

C#
@(Html.Grid("CustomerGrid")
    .SetCaption("Customers")
    .AddColumn(new Column("CustomerId").SetLabel("Id").SetSearch(false))
    .AddColumn(new Column("Name"))
    .AddColumn(new Column("Company"))
    .AddColumn(new Column("EmailAddress").SetLabel("Email Address").SetSearch(false))
    .AddColumn(new Column("Last Modified").SetSearch(false))
    .AddColumn(new Column("Telephone").SetSearch(false))
    .AddColumn(new Column(" ").SetSearch(false).SetCustomFormatter("buttonize").SetWidth(60).SetAlign(Align.Right))
    .SetUrl(Url.Action("List","Customer"))
    .SetAutoWidth(true)
    .SetRowNum(10)
    .SetRowList(new[] { 10, 15, 20, 50 })
    .SetViewRecords(true)
    .SetPager("pager")
    .SetSearchToolbar(true)
    .SetSearchOnEnter(false)) 

Where buttonize is a JavaScript function where the operation column Html is returned.

JavaScript
function buttonize(cellvalue, options, rowobject) {
     return '<a href="http://xprog.blogspot.com">eXtreme Programming</a>';
 }

In a even more advanced scenario, the requested type preferred should be POST, since the default is GET. The SetRequestType method allows the definition of the request type. The previous example uses an array that must return the values in the same order as the column definitions. A more generic solution is to return a JSON object with named properties. The MvcJqGrid supports this scenario by the SetJsonReader method. The SetJsonReader method is used to configure the grid jsonReader so that the JSON data doesn't have to match the column model (ColModel) order of jqGrid. Another feature that is advanced, is the capability to search in each desired column, using different search types. The SetSearchType sets the search type for the column. The seach type can be:

  • Input (Default)
  • Select. The SetSearchTerms method receives the collection of strings that define the select options.
  • Datepicker. The SetSearchDateFormat method allow the definition of the date format.

To enable the toolbar searching SetSearchToolbar must be set to true. The SetSearchOnEnter is used to define when the search is executed:

  • true : the search is executed when the user presses enter
  • false: the search is executed after the user stops typing

The SetRowList creates a dropdownlist in the pager of the grid with the specified number of rows per page.

Now we can create an example using the customer class. The view:

XML
<div style="width: 900px;">
@(Html.Grid("customerGrid")
    .SetRequestType(RequestType.Post)
    .SetJsonReader(new MvcJqGrid.DataReaders.JsonReader { Id="id", RepeatItems = false})
    .SetCaption("Customers")
    .AddColumn(new Column("FirstName").SetWidth(100).SetLabel("First Name"))
    .AddColumn(new Column("LastName").SetWidth(100).SetLabel("Last Name"))
    .AddColumn(new Column("CountryName").SetLabel("Country")
                          .SetSearchType(Searchtype.Select)
                          .SetSearchTerms((string[])ViewBag.Countries))
    .AddColumn(new Column("Phone").SetWidth(100))
    .AddColumn(new Column("BirthDate").SetWidth(80).SetSearchType(Searchtype.Datepicker)
                          .SetSearchDateFormat("yy-mm-dd"))
    .AddColumn(new Column(" ").SetSearch(false).SetCustomFormatter("buttonize")
                                    .SetWidth(25)
                                    .SetAlign(Align.Right))
    .SetUrl(Url.Action("Search", "Customer"))
    .SetAutoWidth(true)
    .SetRowNum(10)
    .SetRowList(new[] { 10, 15, 20, 50 })
    .SetViewRecords(true)
    .SetPager("pager")
    .SetSearchToolbar(true).SetSearchOnEnter(false)     
    )
</div>

The controller that returns JSON with named properties:

C#
public class CustomerController : Controller
{
    public ActionResult Index()
    {
        var countries = new CountryRepository().Search();
        ViewBag.Countries = (from c in countries select c.Name).ToArray();
        return View();
    }

    public JsonResult Search(GridSettings gridSettings)
    {
        List<CustomerSearchResult> customers = null;
        int totalRecords;
        CustomerRepository customerRepository = new CustomerRepository();
            
        CustomerSeachFilter filter = new CustomerSeachFilter();
        if (gridSettings.IsSearch)
        {
            filter.FirstName = gridSettings.Where.rules.Any(r => r.field == "FirstName") ? 
                    gridSettings.Where.rules.FirstOrDefault(r => r.field == "FirstName").data : string.Empty;
            filter.LastName = gridSettings.Where.rules.Any(r => r.field == "LastName") ? 
                    gridSettings.Where.rules.FirstOrDefault(r => r.field == "LastName").data : string.Empty;
            filter.CountryName = gridSettings.Where.rules.Any(r => r.field == "CountryName") ? 
                    gridSettings.Where.rules.FirstOrDefault(r => r.field == "CountryName").data : string.Empty;
            filter.Phone = gridSettings.Where.rules.Any(r => r.field == "Phone") ? 
                    gridSettings.Where.rules.FirstOrDefault(r => r.field == "Phone").data : string.Empty;
            filter.BirthDate = gridSettings.Where.rules.Any(r => r.field == "BirthDate") ? 
            filter.BirthDate = gridSettings.Where.rules.Any(r => r.field == "BirthDate") ? 
                    DateTime.ParseExact(gridSettings.Where.rules.FirstOrDefault(r => r.field == "BirthDate").data, 
                                        "yyyy-MM-dd", null) : DateTime.MinValue;
        }

        customers = customerRepository.Search(filter, 
                                              gridSettings.SortColumn, 
                                              gridSettings.SortOrder, 
                                              gridSettings.PageSize, 
                                              gridSettings.PageIndex, 
                                              out totalRecords);

        var jsonData = new
        {
            total = totalRecords / gridSettings.PageSize + 1,
            page = gridSettings.PageIndex,
            records = totalRecords,
            rows = (
                from c in customers
                select new
                {
                    id = c.CustomerID,
                    FirstName = c.FirstName,
                    LastName = c.LastName,
                    BirthDate = c.BirthDate.ToString("yyyy-MM-dd"),
                    CountryName = c.CountryName,
                    EmailAddress = c.EmailAddress,
                    Phone = c.Phone,
                })
        };
        return Json(jsonData);
    }
}

The example will create the following grid: 

Image 1

The MvcJqGrid search feature also allows the configuration of the seach: 

  • SetSortName - Defines the default seach field for the grid.
  • SetSortOrder - Defines the default sort order, using the SortOrder enumerator for the grid.
  • SetDefaultSearchValue - Sets the default search value for a specific column.

For more information and live examples go to the MvcJqGrid site by pressing here.

The about tab has the links to the license, the source code and documentation. 

 

Note:

The MvcJqGrid has now a Nuget Package with the Id: MvcJqGrid  and the code is in GitHub: https://github.com/robinvanderknaap/MvcJqGrid

 

 

This article was originally posted at http://xprog.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader
Portugal Portugal
I am an Experienced Senior Microsoft Consultant responsible for developing and defining architectures for various projects in a Microsoft environment, using a Service-Oriented Architecture (SOA) and web based applications.
I am also a project manager using agile methodologies and SCRUM.
Software Quality Assurance is a mandatory in every project I am responsible.
As someone said:
“Anyone can program, but not everyone is a programmer...”

Comments and Discussions

 
AnswerRe: AutoWidth Invalid? Pin
Rui Inacio7-Mar-13 3:32
Rui Inacio7-Mar-13 3:32 
QuestionWorking with MvcJqGrid, how to set datatype to local and data as '[]' Pin
sivanand8-Jan-13 1:59
sivanand8-Jan-13 1:59 
QuestionDropdown, checkbox, and other controls within a grid Pin
Rich Sorensen5-Nov-12 6:17
Rich Sorensen5-Nov-12 6:17 
AnswerRe: Dropdown, checkbox, and other controls within a grid Pin
Rui Inacio6-Nov-12 23:24
Rui Inacio6-Nov-12 23:24 
QuestionmvcJqGrid.demo.delete Pin
Juan Bengoa18-Oct-12 10:53
Juan Bengoa18-Oct-12 10:53 
AnswerRe: mvcJqGrid.demo.delete Pin
Rui Inacio22-Oct-12 22:15
Rui Inacio22-Oct-12 22:15 
QuestionHow do I show the add, edit and delete buttons on the pager? Pin
ScottieSLG11-Oct-12 16:49
ScottieSLG11-Oct-12 16:49 
AnswerRe: How do I show the add, edit and delete buttons on the pager? Pin
Rui Inacio22-Oct-12 22:17
Rui Inacio22-Oct-12 22:17 
The MvcjqGrid does not have support for that.
But you can use the client side API of the jqGrid to perform that actions.
QuestionHow to add Enumerable Columns to .AddColumns() instead of adding each Column with .AddColumn Pin
skmuru5-Sep-12 21:57
professionalskmuru5-Sep-12 21:57 
AnswerRe: How to add Enumerable Columns to .AddColumns() instead of adding each Column with .AddColumn Pin
Rui Inacio5-Sep-12 22:10
Rui Inacio5-Sep-12 22:10 
GeneralRe: How to add Enumerable Columns to .AddColumns() instead of adding each Column with .AddColumn Pin
skmuru17-Sep-12 2:43
professionalskmuru17-Sep-12 2:43 
AnswerRe: How to add Enumerable Columns to .AddColumns() instead of adding each Column with .AddColumn Pin
Rui Inacio5-Sep-12 22:13
Rui Inacio5-Sep-12 22:13 
GeneralIs MvcJQGrid is free MVC helper or I have to pay for it later? Pin
rajvi5-Sep-12 10:01
rajvi5-Sep-12 10:01 
GeneralRe: Is MvcJQGrid is free MVC helper or I have to pay for it later? Pin
Rui Inacio5-Sep-12 22:12
Rui Inacio5-Sep-12 22:12 
GeneralRe: Is MvcJQGrid is free MVC helper or I have to pay for it later? Pin
rajvi6-Sep-12 4:01
rajvi6-Sep-12 4:01 
GeneralRe: Is MvcJQGrid is free MVC helper or I have to pay for it later? Pin
Rui Inacio6-Sep-12 4:02
Rui Inacio6-Sep-12 4:02 
GeneralRe: Is MvcJQGrid is free MVC helper or I have to pay for it later? Pin
Jerzy Mieczyński23-Oct-12 23:21
Jerzy Mieczyński23-Oct-12 23:21 
QuestionStrange error with IE9 Pin
Andreas Kroll15-Aug-12 12:51
Andreas Kroll15-Aug-12 12:51 
AnswerRe: Strange error with IE9 Pin
Rui Inacio16-Aug-12 2:03
Rui Inacio16-Aug-12 2:03 
Questionhttp://www.clothes8.org Pin
fkjgjhjhjnj26-Jul-12 3:59
fkjgjhjhjnj26-Jul-12 3:59 
GeneralDynamicQuery Pin
jeffb4224-Jul-12 12:14
jeffb4224-Jul-12 12:14 
GeneralRe: DynamicQuery Pin
Rui Inacio25-Jul-12 23:45
Rui Inacio25-Jul-12 23:45 
GeneralMy vote of 5 Pin
Rupesh Kumar Tiwari24-Jul-12 5:27
Rupesh Kumar Tiwari24-Jul-12 5:27 

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.