MVC 3 Web grid sorting not working

I recently was working a lot with Web Grids, and there was this was one problem that kept coming up again n again, so I have decided to write an article for this.

Lets first see what my web grid code looked like when my sorting was NOT WORKING,

var myGrid = new WebGrid(source: Model.ABC);

@myGrid .GetHtml(

    columns: myGrid .Columns(  
    myGrid .Column("User Name", format: @<text>@item.Username</text>),  
    myGrid .Column("Password", format: @<text>@item.Password</text>),

))

While testing I found that sorting on Password column worked but when I tried sorting on Username column it just didn’t work !

SOLUTION:

After a little googling and going over stackOverflow QA I finally found the actual problem.

This happens because the grid column names must correspond to your fields or db columns. The Method which generates URL in grid header compares “sort” from url query string with bounded columns and with grid column name. These must be exactly the same.

So because I had used “User Name” and not “Username”, sorting on my username column did not work.

Corrected code : Use **columnName:, **to specify column names and **header: **to specify table header

var myGrid = new WebGrid(source: Model.ABC);

    @myGrid .GetHtml(

    columns: myGrid .Columns(  
    myGrid .Column(header: "User Name", columnName: "Username" , format: @<text>@item.Username</text>),  
    myGrid .Column(header: "Password", columnName: "Password" ,format: @<text>@item.Password</text>),

))

Hope this helps you too !

About Yasser Shaikh

Hello, I am a Web Dev, employed with Media.Net where I primarily work on ASP.NET MVC and Angular JS based developement.

Questions? Enquiries? Comments? Or even just want to say “Hi” to me, you are welcome to all of that. Just drop me a message at “mail@yassershaikh.com” and I’ll get back to you as soon as possible.

Cheers !

4 comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>