Sorting in webgrid in ASP.NET MVC

sorting in webgrid in mvc3
Webgrid sorting in ASP.NET MVC

Very common and frequently used functionality is display data in grid, in mvc we have grid but with very less inbuilt features where most of the things have to do manually like webgrid sorting. This article will cover how to sorting in webgrid.
We are displaying student data in ASP.NET webgrid.

Sorting in webgrid in ASP.NET MVC

Sorting in webgrid in ASP.NET MVC

Step 1: Create Controller with a Action method which will return list of student to view.

        public ActionResult getStudent(string sort= "", string sortdir="")
        {
            List<Student> students = Student.getStudent();
            IQueryable<Student> stud = SortIQueryable<Student>(Student.getStudent().AsQueryable(), sort, sortdir);
            return View(stud);
        }

Notice the input parameter to getStudent method are sort, sortdir (optional), Where sore is name od column and sortdir is sorting direction ASC or DESC, If these values are empty we will return list as it is or return list as per sorting.

SortIQueryable is a function accept the student list, sort column and sort direction and return sorted list as per requirement.

	public static 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);
        }

Step 2: Create View

First add model as

@model  IQueryable<Sample.Models.Student>

And create grid as below

@{
     var grid = new WebGrid(Model, canSort:true);
}

<div  id="gridContent" style=" padding:20px; " class="datagrid" >
<h2>Student</h2>
@grid.GetHtml(

        mode: WebGridPagerModes.All,
        columns:
            grid.Columns(
            grid.Column(columnName: "Name", header: "Name", format: @<text>@item.Name</text>),
            grid.Column(columnName: "SchoolName", header: "school Name", format: @<text>@item.SchoolName</text>),
            grid.Column(columnName: "Address", header: "Address", format: @<text>@item.Address</text>),
            grid.Column(columnName: "City", header: "City", format: @<text>@item.City</text>),
            grid.Column(columnName: "State", header: "State", format: @<text>@item.State</text>)
           ))
</div>

Notice canSort:true which enable sorting default true and one more important thing is columnName in grid.Column should be name of proprty in list it will come as sort ( column name )in controller.

Complete code
View

@model  IQueryable<Sample.Models.Student>
@{
    ViewBag.Title = "getStudent";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<style type="text/css" > 
.datagrid{ background-color:White; }
.datagrid table { margin: 1em; border-collapse: collapse; }
td, th { padding: .3em; border: 1px #ccc solid; }
thead { background: #E8EEF4; }
</style>

@{
    var grid = new WebGrid(Model, canSort:true);
}

<div  id="gridContent" style=" padding:20px; " class="datagrid" >
<h2>Student</h2>
@grid.GetHtml(

        mode: WebGridPagerModes.All,
        columns:
            grid.Columns(
            grid.Column(columnName: "Name", header: "Name", format: @<text>@item.Name</text>),
            grid.Column(columnName: "SchoolName", header: "school Name", format: @<text>@item.SchoolName</text>),
            grid.Column(columnName: "Address", header: "Address", format: @<text>@item.Address</text>),
            grid.Column(columnName: "City", header: "City", format: @<text>@item.City</text>),
            grid.Column(columnName: "State", header: "State", format: @<text>@item.State</text>)
           ))
</div>

Controller


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Sample.Models;
using System.Linq.Expressions;

namespace Sample.Controllers
{
    public class StudentController : Controller
    {
        public ActionResult getStudent(string sort= "", string sortdir="")
        {
            List<Student> students = Student.getStudent();
            IQueryable<Student> stud = SortIQueryable<Student>(Student.getStudent().AsQueryable(), sort, sortdir);
            return View(stud);
        }

        public static 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);
        }
    }
}

Relevant links
Sorting in webgrid in ASP.NET MVC
Delete Multiple webgrid row using jQuery
Efficient Paging and Sorting with WebGrid Web Helper – ASP.NET MVC
ASP.NET MVC3 webgrid conditional statement on column (if, if else loop)
Efficient Paging with WebGrid Web Helper – ASP.NET MVC
ASP.NET MVC Web Grid Style

Advertisements
This entry was posted in ASP.NET MVC Web Grid, MVC and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s