KallDrexx
KallDrexx

Reputation: 27813

Can't figure out how to use JqGrid correctly with Asp.net MVC and Linq to Sql

I seem to be having issues with getting my jqgrids working well with linq to sql in my asp.net mvc project.

The issue I am having is correctly using the sidx and sord parameters. Most resources I find say to do something like

var questions = context.Questions
  .OrderBy(sidx + " " + sord)
  .Skip(pageIndex * pageSize)
  .Take(pageSize);

In Visual Studio 2010 (.net 4 project, MVC2) I get a compile error on the order by because it seems there is no linq orderby extension that takes just a string as a parameter, they all want a delegate/lamda.

How can I implement ordering into my app so my grids can sort properly by columns?

Upvotes: 0

Views: 607

Answers (2)

Vasil Popov
Vasil Popov

Reputation: 1258

If you add "using System.Linq.Dynamic;" the code you pasted should work properly.

There is a small consideration here: OrderBy and Skip goes together, so if you want to skip to a record, should specify OrderBy. I solved this by checking whether there is posted orderby field param.

using System.Linq.Dynamic;
...

{
    var questions = context.Questions;
    if (!string.IsNullOrEmpty(sidx))
        questions = questions.OrderBy(sidx + " " + sord).Skip(pageIndex * pageSize);

    return questions.Take(pageSize);
}

This topic is useful as well: jqGrid, Problem with sorting Linq expression

Upvotes: 0

Jonny Cundall
Jonny Cundall

Reputation: 2622

you can make method that translates the strings into lambda expressions. I've not tested this but it could be like this:

private Expression<Func<Person, T>> orderbyExpression(string column)
{
    switch (column)
    {
       case: "Name":
           return p => p.Name;

       case: "Sex":
          return p => p.Sex;
    }

}

you'll have to sort out the asc/desc setting seperately as well

Upvotes: 1

Related Questions