开发者

MvcContrib Grid Sorting

Am testing out MvcContrib's grid for sorting.

Am using LightSpeed as my ORM

Problem: getting compile error on: listOfRfidTags = ...

The type arguments for method 'System.Linq.Enumerabl开发者_开发问答e.OrderBy(System.Collections.Generic.IEnumerable, System.Func, System.Collections.Generic.IComparer)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

public ActionResult Index(GridSortOptions sort)
        {
            IEnumerable<RfidTag> listOfRfidTags = uow.RfidTags;
            if(sort.Column != null) {
                listOfRfidTags = listOfRfidTags.OrderBy(sort.Column, sort.Direction);
            }
            ViewData["sort"] = sort;
            return View(listOfRfidTags);
        }

view:

@Html.Grid(Model).Columns(column =>{
    column.For(a => Html.ActionLink("Edit", "Edit", new { id = a.Id })).Named("Edit");
    column.For(a => a.TagCode).Named("TagCode").Sortable(true);
    column.For(a => a.Number);
})


You are getting this compiling error because you are trying to use an OrderBy extension method that is only defined in MvcContrib and not in System.Linq.

In order to fix it, you just need to use the following line:

using MvcContrib.Sorting;

And then you can use the OrderBy method as in your original code:

listOfRfidTags = listOfRfidTags.OrderBy(sort.Column, sort.Direction);

Although itowlson answer works, he just reimplements what the OrderBy extension method in MvcContrib already does (see SortExtensions.cs).


The OrderBy extension method takes a delegate for getting the sort key, not a column and direction. So this line:

listOfRfidTags = listOfRfidTags.OrderBy(sort.Column, sort.Direction);

needs to look something like this:

listOfRfidTags = listOfRfidTags.OrderBy(r => r.SomeProperty);

(or OrderByDescending depending on the sort.Direction). The trouble is that SomeProperty can't be determined at compile time because you want it to come from sort.Column. This means that if you want to use LINQ then you'll probably need to use Dynamic LINQ or Reflection to extract the property you want to sort on e.g.

PropertyInfo property = typeof(RfidTag).GetProperty(sort.Column);
listOfRfidTags = listOfRfidTags.OrderBy(r => property.GetValue(r));

However, since you are using LightSpeed as your ORM, you can bypass LINQ and use the core API, which does allow dynamic column names:

Order order = Order.By(sort.Column);
if (sort.Direction == SortDirection.Descending))
  order = order.Descending();
IList<RfidTag> listOfRfidTags = uow.Find<RfidTag>(new Query { Order = order });

This has the side benefit that the sorting will happen on the database instead of in the Web application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜