【问题标题】:How should I implement sorting with Linq to Sql and ASP.NET MVC?我应该如何使用 Linq to Sql 和 ASP.NET MVC 实现排序?
【发布时间】:2011-08-22 04:10:43
【问题描述】:

我有一个显示产品列表的 ASP.NET MVC 应用程序。

 // Product Controller
 public ActionResult List(string sort, int page)
 {
     var products = _productService.GetProducts(page, sort);
     return View(products);
 }

 // ProductService.cs
 public IEnumerable<Products> GetProducts(int pageIndex, string sort)
 {
     return _productRepository.GetProducts(pageIndex, 50, sort);
 }


 // ProductsRepository.cs
 public IEnumerable<Products> GetProducts(int pageIndex, int pageSize, string sort)
 {
     using(var db = new ShopDataContext())
     {
          return db.Products.OrderBy(??).Skip(pageIndex * pageSize).Take(pageSize).ToList();
     }
 }

我有一个非常简单的服务层和存储库。

如何通过我从操作的查询字符串中提取的任意排序字符串/表达式对我的 Linq to SQL 查询进行排序?

/products?sort=hot&page=2

【问题讨论】:

    标签: c# asp.net-mvc linq-to-sql


    【解决方案1】:

    您可以使用 Dynamic Linq 来执行此操作,然后您可以简单地制作 OrderBy("Hot ASC") 之类的东西。检查以下链接:

    Dynamic LINQ

    【讨论】:

      【解决方案2】:

      这个页面会更好

      http://www.asp.net/entity-framework/tutorials/sorting-filtering-and-paging-with-the-entity-framework-in-an-asp-net-mvc-application

      您也可以使用 pagedlist.mvc 作为分页列表

      https://github.com/TroyGoode/PagedList

      非常简单,如果你安装了 mvc 版本,你只需要在查看此代码时编写,然后自动创建所有页面和下一步按钮

      @Html.PagedListPager((IPagedList)ViewBag.OnePageOfProducts, page => Url.Action("Index", new { page = page }))
      

      如果您在任何步骤中获得堆栈,请询问

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-09-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多