开发者

How should I implement sorting with Linq to Sql and ASP.NET MVC?

开发者 https://www.devze.com 2023-03-29 13:11 出处:网络
I have an ASP.NET MVC application where I\'m displaying a list of Products. // Product Controller public ActionResult开发者_如何学编程 List(string sort, int page)

I have an ASP.NET MVC application where I'm displaying a list of Products.

 // 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();
     }
 }

I have a very simple service layer and repository.

How can I sort my Linq to SQL query by some arbitrary sort string/expression that I pull from the query string of my action?

/products?sort=hot&page=2


You can use the Dynamic Linq for doing this and then you can simply make something like OrderBy("Hot ASC"). Check below link:

Dynamic LINQ


this page would help better

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

also you can use pagedlist.mvc for your paginated list

https://github.com/TroyGoode/PagedList

it is so simple and if you install the mvc version you just need to write on view this code then all pages and next buttons created automatically

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

if you get stack on any step please ask

0

精彩评论

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