MvcContrib Grid Sorting

China☆狼群 提交于 2019-12-06 10:08:55

问题


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.Enumerable.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);
})

回答1:


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.




回答2:


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).



来源:https://stackoverflow.com/questions/5423728/mvccontrib-grid-sorting

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!