20 tips for ASP. net mvc 3 Development (7) [20 Recipes for Programming MVC 3]: sort the list

Source: Internet
Author: User
Tags actionlink

Topics

There is a large list (for example, a list of books), and it is very difficult to find one. If you sort an item in the list, it is helpful for searching.

 

Solution

Update the column title of the book list to a link. When the link is clicked, the content of the selected columns will be sorted through Linq (you can click the title link again to switch between ascending and descending order ).

 

Discussion

I was a little surprised when I added sorting and automatically generated views compared to the framework I used before. We hope that the external MVC version can become part of the overall framework. For more information, see the example on ASP. net mvc website homepage. We need to define a Switch statement, and copy a Case for sorting of each column. Fortunately, there are only five items in this case that need to be sorted. This is not too bad. If you want to sort by the author or other columns in the future, you only need to copy this Case. In the following example, we will use the Dynamic Linq Library to simplify the work.

The Linq library can be queried from the database and return strongly typed results. Programming tools provide intelligent sensing support and compile-time error detection. Many of our coplaying functions are based on these functions.

Add support for generating sorting in the BooksController, Books, and Index views. The code for the Index view is as follows:

@model IEnumerable<MvcApplication4.Models.Book>
<p>
@Html.ActionLink((string)ViewBag.CreateLink, "Create")
</p>

<table>
<tr>
<th>
@Html.ActionLink((string)ViewBag.TitleDisplay,
"Index", new { sortOrder = ViewBag.TitleSortParam })
</th>
<th>
@Html.ActionLink((string)ViewBag.IsbnDisplay,
"Index", new { sortOrder = ViewBag.IsbnSortParam })
</th>
<th>
@ViewBag.SummaryDisplay
</th>
<th>
@Html.ActionLink((string)ViewBag.AuthorDisplay,
"Index", new { sortOrder = ViewBag.AuthorSortParam })
</th>
<th>
@ViewBag.ThumbnailDisplay
</th>
<th>
@Html.ActionLink((string)ViewBag.PriceDisplay,
"Index", new { sortOrder = ViewBag.PriceSortParam })
</th>
<th>
@Html.ActionLink((string)ViewBag.PublishedDisplay,
"Index", new { sortOrder =
ViewBag.PublishedSortParam })
</th>
<th></th>
</tr>

@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Isbn)
</td>
<td>
@Html.DisplayFor(modelItem => item.Summary)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.DisplayFor(modelItem => item.Thumbnail)
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.Published)
</td>
<td>
@Html.ActionLink((string)ViewBag.EditLink,
"Edit", new { id=item.ID }) |
@Html.ActionLink((string)ViewBag.DetailsLink,
"Details", new { id = item.ID }) |
@Html.ActionLink((string)ViewBag.DeleteLink,
"Delete", new { id = item.ID })
</td>
</tr>
}
</table>

In the preceding example, we modified the previously created th tag and used Html helper to convert static text to HTML links.

Next, you need to modify the Index method in BookController. This method will accept a new sorting parameter, which will specify the columns for sorting results when executing a query in Linq. A new variable is created in ViewBag to store the sorting conditions of each column.

Microsoft provides a new free extension of the DynamicQuery class for Linq, which allows dynamic generation of query statements at runtime and download to C # by accessing the http://msdn2.microsoft.com/en-us/vcsharp/bb894665.aspx. Download and decompress the package to a location on the hard disk. Find the file in the directory and add it to the project. \ CSharpSamples \ LinqSamples \ DynamicQuery \ Dynamic. cs ". To better organize the code, create the "Utils" folder in the project, right-click the "Utils" folder and choose "add"> "existing items ", then find the dynamic class in the browser window (or drag the file to the "Utils" directory ).

After the dynamic class is added, edit and update BooksController:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Web;
using System.Web.Mvc;
using MvcApplication4.Models;
using MvcApplication4.Resources;

namespace MvcApplication4.Controllers
{
public class BooksController : Controller
{
private BookDBContext db = new BookDBContext();
//
// GET: /Books/
public ViewResult Index(string sortOrder)
{
#region ViewBag Resources

#endregion
#region ViewBag Sort Params
// Define the sort orders - if the same link is
// clicked twice, reverse the direction from
// ascending to descending
ViewBag.TitleSortParam = (sortOrder == "Title")
? "Title desc" : "Title";
ViewBag.IsbnSortParam = (sortOrder == "Isbn")
? "Isbn desc" : "Isbn";
ViewBag.AuthorSortParam = (sortOrder == "Author")
? "Author desc" : "Author";
ViewBag.PriceSortParam = (sortOrder == "Price")
? "Price desc" : "Price";
ViewBag.PublishedSortParam =
(String.IsNullOrEmpty(sortOrder))
? "Published desc" : "";
// Default the sort order
if (String.IsNullOrEmpty(sortOrder))
{
sortOrder = "Published desc";
}
#endregion
var books = db.Books.OrderBy(sortOrder);
return View(books.ToList());
}
...
}

}

Reference

System. Linq. Expressions namespace original book Address Book source code

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.