3

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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.