ASP. net mvc Practice Series 8-solutions for pagination after Query

Source: Internet
Author: User
Tags actionlink

I. Preface:

Pagination in the GridView uses post, so the content in the query form can be stored in ViewState, which can be used during page turning to make it easier to implement, in mvc, we have to do this by ourselves. pagination in Contrib can only cope with simple applications, but does not process the pagination of the query results. Next we will modify this paging program.

2. Preparations

First, prepare a data source.

Data Source preparation
1 public class News
2 {
3 public int ID {get; set ;}
4 public string Author {get; set ;}
5 public string Title {get; set ;}
6 public DateTime CreateTime {get; set ;}
7}
8. public class ListNews
9 {
10 public static List <News> GetList ()
11 {
12 List <News> list = new List <News> ();
13 list. Add (new News {ID = 1, Author = "lfm1", Title = "60 th anniversary of the People's Republic of China", CreateTime = DateTime. Now });
14 list. Add (new News {ID = 2, Author = "lfm2", Title = "61 Anniversary of the People's Republic of China", CreateTime = DateTime. Now. AddHours (1 )});
15 list. Add (new News {ID = 3, Author = "lfm3", Title = "62 Anniversary of the People's Republic of China", CreateTime = DateTime. Now. AddHours (2 )});
16 list. Add (new News {ID = 4, Author = "lfm3", Title = "63 Anniversary of the People's Republic of China", CreateTime = DateTime. Now. AddHours (3 )});
17 list. Add (new News {ID = 5, Author = "lfm2", Title = "64 Anniversary of the People's Republic of China", CreateTime = DateTime. Now. AddHours (4 )});
18 list. Add (new News {ID = 6, Author = "lfm1", Title = "60 th anniversary of the People's Republic of China", CreateTime = DateTime. Now });
19 list. Add (new News {ID = 7, Author = "lfm2", Title = "61 Anniversary of the People's Republic of China", CreateTime = DateTime. Now. AddHours (1 )});
20 list. Add (new News {ID = 8, Author = "lfm3", Title = "62 Anniversary of the People's Republic of China", CreateTime = DateTime. Now. AddHours (2 )});
21 list. Add (new News {ID = 9, Author = "lfm3", Title = "63 Anniversary of the People's Republic of China", CreateTime = DateTime. Now. AddHours (3 )});
22 list. Add (new News {ID = 10, Author = "lfm2", Title = "64 Anniversary of the People's Republic of China", CreateTime = DateTime. Now. AddHours (4 )});
23 list. Add (new News {ID = 11, Author = "lfm2", Title = "64 Anniversary of the People's Republic of China", CreateTime = DateTime. Now. AddHours (4 )});
24 list. Add (new News {ID = 12, Author = "lfm1", Title = "60 th anniversary of the People's Republic of China", CreateTime = DateTime. Now });
25 list. Add (new News {ID = 13, Author = "lfm2", Title = "64 Anniversary of the People's Republic of China", CreateTime = DateTime. Now. AddHours (4 )});
26 list. Add (new News {ID = 14, Author = "lfm1", Title = "60 th anniversary of the People's Republic of China", CreateTime = DateTime. Now });
27 list. Add (new News {ID = 15, Author = "lfm2", Title = "64 Anniversary of the People's Republic of China", CreateTime = DateTime. Now. AddHours (4 )});
28 list. Add (new News {ID = 16, Author = "lfm1", Title = "60 th anniversary of the People's Republic of China", CreateTime = DateTime. Now });
29
30 return list;
31}
32}
Then add a View:

View
1 <% Html. BeginForm (); %>
2 Title: <% = Html. TextBox ("title", Request. Form ["title"]? Request. QueryString ["title"]) %>
3 Author: <% = Html. TextBox ("author", Request. Form ["author"]? Request. QueryString ["author"]) %>
4 <input type = "submit" value = "query"/>
5 <% Html. EndForm (); %>
6 <% = Html. Grid (Model). Columns (column => {
7 column. For (x => x. ID). Named ("News ID ");
8 column. For (x => Html. ActionLink (x. Title, "NewsDetils", new {newsId = x. ID}). DoNotEncode ();
9 column. for (x => x. author ). header ("<th>" + Html. actionLink ("author", "CustomPager", new {desc = Convert. toBoolean (ViewData ["desc"]), sortName = "Author"}) + "</th> ");
10 column. For (x => x. CreateTime );
11 })
12%>
13
14 <% = Html. Pager (Model, ViewData ["search"]) %>
The paging code here is slightly different from the Contrib code. Let's explain the different reasons later.

Add a Controller:

Controller
1 public ActionResult CustomPager (int? Page)
2 {
3 int pageSize = 3;
4 int pageNumber = page ?? 1;
5 var list = ListNews. GetList ()
6. Where (p => p. Title. Contains (Request. QueryString ["title"]? ""))
7. Where (p => p. Author. Contains (Request. QueryString ["author"]? ""));
8
9 var pageList = list. Skip (pageNumber-1) * pageSize). Take (pageSize );
10 int total = list. Count ();
11 CustomPagination <News> customes = new CustomPagination <News> (pageList, pageNumber, pageSize, total );
12
13 return View (customes );
14}
15 [AcceptVerbs (HttpVerbs. Post)]
16 public ActionResult CustomPager (FormCollection formCollection)
17 {
18 int pageSize = 3;
19 int pageNumber = 1;
20 var list = ListNews. GetList (). Where (p => p. Title. Contains (Request. Form ["title"])
21. Where (p => p. Author. Contains (Request. Form ["author"]);
22 int total = list. Count ();
23 var pageList = list. Skip (pageNumber-1) * pageSize). Take (pageSize );
24 CustomPagination <News> customes = new CustomPagination <News> (pageList, pageNumber, pageSize, total );
25 Dictionary <string, string> d = new Dictionary <string, string> ();
26 d. Add ("title", Request. Form ["title"]);
27 d. Add ("author", Request. Form ["author"]);
28 ViewData ["Search"] = d;
29 return View (customes );
30}
Note: For details about this part, see ASP. net mvc Practice Series 7-Grid implementation (the following section uses Contrib implementation)

Iii. Page source code analysis of Contrib

We first copy the source code in the Pagination and Pager folders. After analysis, we know that CustomPagination is a set of IPagination interfaces, we can use Pager for paging by integrating data into CustomPagination. PaginationExtensions is a static class that assists HtmlHelper in using the extension method.



Iv. Pager class Transformation

After analysis, we found that Pager outputs the paging string to the foreground using the ToString () method. Therefore, we need to transform the ToString () method of Pager first. We often want to display pages like this:

Previous Page 1 2 3 4 5 6 next page, so the ToString () method is transformed as follows:

ToString Method
1 public override string ToString ()
2 {
3 if (_ pagination. TotalItems = 0)
4 {
5 return null;
6}
7
8 var builder = new StringBuilder ();
9
10 builder. Append ("<div class =" + _ pageStyle + "> ");
11
12 if (_ pagination. PageNumber> 1)
13 builder. Append (CreatePageLink (_ pagination. PageNumber-1, _ pagePrev ));
14 else
15 builder. Append (CreatePageText (_ pagePrev ));
16 for (int I = 0; I <_ pagination. TotalPages; I ++)
17 {
18 var current = I + 1;
19 if (current = _ pagination. PageNumber)
20 {
21 builder. Append (CreatePageText (current. ToString ()));
22}
23 else
24 {
25 builder. Append (CreatePageLink (current, current. ToString ()));
26}
27 builder. Append ("");
28}
29
30 if (_ pagination. PageNumber <_ pagination. TotalPages)
31 builder. Append (CreatePageLink (_ pagination. PageNumber + 1, _ pageNext ));
32 else
33 builder. Append (CreatePageText (_ pageNext ));
34 builder. Append (@ "</div> ");
35
36 return builder. ToString ();
37}
Here we need to explain how paging will be implemented. In this solution, we will attach the query information to the paging Url, first, we will add the conditions to be appended to a Dictionary <string, string> class, and then pass it to the Pager class for processing.

Next we will transform the CreateQueryString method:

CreateQueryString
1 private string CreateQueryString (NameValueCollection values)
2 {
3 var builder = new StringBuilder ();
4 if (_ searchValues! = Null)
5 {
6 builder = GetSearchPage (values );
7}
8 else
9 {
10 foreach (string key in values. Keys)
11 {
12 if (key = _ pageQueryName)
13 // Don't re-add any existing 'page' variable to the querystring-this will be handled in CreatePageLink.
14 {
15 continue;
16}
17
18 foreach (var value in values. GetValues (key ))
19 {
20 builder. AppendFormat ("& amp; {0 }={ 1}", key, HttpUtility. UrlEncode (value ));
21}
22}
23}
24
25
26 return builder. ToString ();
27}
28 /// <summary>
29 // organize the paging string based on the input _ searchValues
30 /// </summary>
31 // <param name = "values"> </param>
32 /// <returns> </returns>
33 private StringBuilder GetSearchPage (NameValueCollection values)
34 {
35 var builder = new StringBuilder ();
36 Dictionary <string, string> dictionary = new Dictionary <string, string> ();
37 foreach (var item in _ searchValues)
38 {
39 dictionary. Add (item. Key, item. Value );
40}
41 foreach (string key in values. Keys)
42 {
43 if (key = _ pageQueryName)
44 // Don't re-add any existing 'page' variable to the querystring-this will be handled in CreatePageLink.
45 {
46 continue;
47}
48
49 foreach (var value in values. GetValues (key ))
50 {
51 if (_ searchValues. Keys. Contains (key ))
52 {
53 builder. AppendFormat ("& amp; {0 }={ 1}", key, HttpUtility. UrlEncode (dictionary [key]);
54 dictionary. Remove (key );
55}
56 else
57 {
58 builder. AppendFormat ("& amp; {0 }={ 1}", key, HttpUtility. UrlEncode (value ));
59}
60
61}
62
63}
64 foreach (var item in dictionary)
65 {
66 builder. AppendFormat ("& amp; {0 }={ 1}", item. Key, HttpUtility. UrlEncode (item. Value ));
67
68}
69 return builder;
70}

The GetSearchPage method is mainly added here. This method organizes display paging strings Based on the query conditions passed in by the client.

V. Disadvantages:

Because it is implemented by adding URLs, there may be problems when there are too many query conditions. I will implement a post scheme for your reference when I have time. In addition, you must note that the query string names in the url cannot be repeated. If the query string is repeated, It will be replaced directly. For details, see the source code.

6. Download 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.