Click here to Skip to main content
15,888,984 members
Articles / Web Development / HTML

An Example to Use jQuery Grid Plugin in MVC - Part 1

Rate me:
Please Sign up or sign in to vote.
4.70/5 (17 votes)
1 Aug 2011CPOL7 min read 224.3K   10.4K   71  
This article presents a simple example on how to use jQuery Grid Plugin in MVC.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using jqGridExamplePart1.Models;
using System.Linq.Expressions;

namespace jqGridExamplePart1.Controllers
{
    public class jQGridController : Controller
    {
        [HttpPost]
        public ActionResult LoadjqData(string sidx, string sord, int page, int rows,
                bool _search, string searchField, string searchOper, string searchString)
        {
            // Get the list of students
            var students = StudentRepository.GetStudents().AsQueryable();

            // If search, filter the list against the search condition.
            // Only "contains" search is implemented here.
            var filteredStudents = students;
            if (_search)
            {
                filteredStudents = students.Where(s =>
                    (typeof(Student).GetProperty(searchField).GetValue(s, null) == null) ? false :
                        typeof(Student).GetProperty(searchField).GetValue(s, null)
                        .ToString().Contains(searchString));
            }

            // Sort the student list
            var sortedStudents = SortIQueryable<Student>(filteredStudents, sidx, sord);

            // Calculate the total number of pages
            var totalRecords = filteredStudents.Count();
            var totalPages = (int)Math.Ceiling((double)totalRecords / (double)rows);

            // Prepare the data to fit the requirement of jQGrid
            var data = (from s in sortedStudents
                        select new
                        {
                            id = s.Id,
                            cell = new object[] { s.Id, s.Name,
                            s.Score, s.Enrollment.ToString("MM/dd/yyyy") }
                        }).ToArray();

            // Send the data to the jQGrid
            var jsonData = new
            {
                total = totalPages,
                page = page,
                records = totalRecords,
                rows = data.Skip((page - 1) * rows).Take(rows)
            };

            return Json(jsonData);
        }

        // Utility method to sort IQueryable given a field name as "string"
        // May consider to put in a cental place to be shared
        private IQueryable<T> SortIQueryable<T>(IQueryable<T> data, string fieldName, string sortOrder)
        {
            if (string.IsNullOrWhiteSpace(fieldName)) return data;
            if (string.IsNullOrWhiteSpace(sortOrder)) return data;

            var param = Expression.Parameter(typeof(T), "i");
            Expression conversion = Expression.Convert(Expression.Property(param, fieldName), typeof(object));
            var mySortExpression = Expression.Lambda<Func<T, object>>(conversion, param);

            return (sortOrder == "desc") ? data.OrderByDescending(mySortExpression)
                : data.OrderBy(mySortExpression);
        }

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
United States United States
I have been working in the IT industry for some time. It is still exciting and I am still learning. I am a happy and honest person, and I want to be your friend.

Comments and Discussions