20 secrets of MVC3-(7) sorting results

Source: Internet
Author: User
Tags actionlink

 

Problem

You have a very large list (for example, a list of books), and you cannot easily find what you want. Sorting by a column in the list can help you quickly find what you want.

Solution

Add a link to the title of the book list. When you click a link, use the Dynamic Linq Library to sort the results and select columns. (Ascending or descending ). If you click the link again, the order will be reversed.

Discussion

Compared with the previously used framework, I was a little surprised to add a sort in the automatically generated View. We hope that in future versions of MVC, scaffolding will help us do this. Another thing I need to do is to provide one or more options on the homepage of ASP. NET MVC to switch the sorting. In the case of books, only five columns need to be sorted, which is not too bad. However, if this function is applied to other examples. It may be the author column, and the workload will increase! In the example below, it would be much easier to use Dynamic Linq Library!

By default, the linq class library allows strong expressions to generate results from the database. This has some advantages, such as comprehensive intelligent awareness and error messages during compilation. Of course, as I mentioned above, building those useful functions has also become a huge workload.

To support sorting, make the following changes in BooksController and Books index view:

@ Model IEnumerable <MvcApplication. Models. Book>

<H2> @ ViewBag. Title

<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, the <th> label created on the front is no longer static text. You have replaced ActionLink with HTML link in HTML Helper.

The Index action of BookController also needs to be updated. This action will receive a new parameter: sortOrder. Next, we will use LINQ to sort the results based on this column. Microsoft has provided a free dynamic query class, which is an extension under the linq, allowing you to query dynamically based on expressions. The namespace is using System. Linq. Dynamic. Download the C # version of this class can access: http://msdn2.microsoft.com/en-us/vcsharp/bb894665.aspx !) After downloading, decompress the package. The dynamic linq query class can be found here :~ \ CSharpSamples \ LinqSamples \ Dynamic

Query \ DynamicQuery \ Dynamic. cs. This file must be added to the project. To properly organize the project structure. I suggest you add it to the Utils directory. Right-click the Utils directory-> Add-> existing items, and find the dynamic linq

Class (or drag the folder to the Utils directory ).

Update BooksController as follows:

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 MvcApplication. Models;

Using MvcApplication. Resources;

Namespace MvcApplication. 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 ());

}

 

}

}

 

The preceding example allows sorting based on the input sortOrder variable. The above code is slightly insecure to prove

The process of executing a dynamic LINQ query with minimal impact. Because this variable can be passed in through a URL, it is very important to add some verification for the input data. This ensures that users cannot perform malicious behaviors.

 

For more information, see

System. Linq. Expressions Namespace

 


Author technical brother

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.