20 secrets of mvc3-(17) shutter Paging

Source: Internet
Author: User

Problem

Today, many websites interact with databases. If your website receives a large amount of traffic, SQL queries are used to retrieve data, which is quite intense. More importantly, because a common user clicks a link that reaches your website within 15 seconds, retrieval and content generation may be unnecessary, especially when the content is "region collapse" (invisible without scrolling ). To help solve this problem, the content will be loaded as needed. Enough content will be loaded, making the page feel increasing as you scroll down and read more content will be filled without affecting the user experience.

Solution

The asynchronous controller and jquery are used to load content as needed. When users start to scroll through the content of the website, the content is loaded step by step.

Discussion

Asynchronous controller may not be fully utilized in many MVC applications. The most likely reason is that people do not know them, and more importantly, they do not know when to use them. The following is an excerpt from the msdn Website:

"In applications, thread hunger may occur. You can configure asynchronous action processing. Asynchronous requests and synchronous requests take the same time. For example, if a request takes two seconds for a network call, the request takes two seconds, whether synchronous or asynchronous. However, in an asynchronous call, when the server responds to wait for its first request to complete, its response to other requests is not blocked. Therefore, when many requests call long-running operations, asynchronous requests will prevent requests from queuing. "

In this example, asynchronous requests are the perfect solution. Because it enables the IIS server to process more important requests, such as a new user accessing the website for the first time. Loading users' on-demand content is not very important, because most people do not even pay attention to loading additional content. On a typical social networking website, most activities may contain users' opinions. In the previous recipe, a comment function was created. In this example, the website page will be updated to list recent comments. A few comments will be displayed, so a scroll bar will appear. Once the user starts to scroll, the asynchronous controller of an Ajax request will retrieve other comments.

First, the home/index view needs to be updated to display recent comments. To provide the context content of some comments, the basic details about the book will also be displayed as a link to the book. Therefore, this view will simply call the render function in the view and create it below:

 

@ Model ienumerable <  Mvcapplication  . Models. bookcomment  > 
@{
Viewbag. Title = "home page ";
}
< H2 > @ Viewbag. Message </ H2 >
< P >
To learn more about ASP. net mvc visit < A Href = "Http://asp.net/mvc" Title = "ASP. net mvc Website" >
Http://asp.net/mvc </ A > .
</ P >
< Script Type = "Text/JavaScript" >
VaR Lasty = 0 ;
VaR Currenty = 0 ;
VaR Page = 1 ;
VaR Maxpages = @ Viewbag. maxpages;
$ (Window). Scroll ( Function (){
If (Page < Maxpages ){
Currenty = $ (Window). scrolltop ();
If (Currenty - Lasty > 200 * (Page - 1 )){
Lasty = Currenty;
Page ++ ;
$. Get ( ' Commentfeed/comments? Page = ' + Page,
Function (Data ){
$ ( ' # Comments ' ). Append (data );
});
}
}
});
</ Script >
< Div ID = "Comments" >
< H2 >
Recent comments </ H2 >
@ Html. Partial ("../commentfeed/comments", Model)
</ Div >

 

In the above example, some complex JavaScript code is also available when performing a scrolling window.CodeYes. Some global JavaScript variables are defined to maintain the current "Y" rolling position, the final "Y" rolling position, and the currently retrieved page. When the scrolltop position in the window minus the last scroll position is greater than a specific number, use ajax to retrieve the new book comment and append it to the comment list.

 

You will correct the specific number based on your website. Based on the Content height, make sure that new content is always retrieved in advance.
Next, homecontroller needs to update the list of retrieved book reviews. The comments are sorted in descending order to ensure that the comments on the latest creation date are first displayed. To prevent intense database loads, all comments will be reduced to a small number. This should be adjusted according to your website to ensure that there is enough content, resulting in scrolling. In the following example, we recommend that you set the value to 3. The maximum number of pages depends on the total number of comments divided by 3. Once the maximum number of comments has been returned, the maximum number of pages is used to prevent further Ajax calls.

 Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. Web. MVC;
Using System. Globalization;
Using System. Data. entity;
Using Mvcapplication. models;

Namespace Mvcapplication. Controllers
{
Public Class Homecontroller: Controller
{
Private Bookdbcontext DB = New Bookdbcontext ();

Public Actionresult index ()
{
Viewbag. Message = " Welcome to ASP. net mvc! " ;

// Get our recent comments
VaR Bookcomments = dB. bookcomments. Include (B => B. Book). orderbydescending (B => B. created). Take ( 3 );
VaR Count = dB. bookcomments. Count ();
Viewbag. maxpages = count/ 3 + 1 ;

Return View (bookcomments );
}

Public Actionresult changelanguage ( String Language)
{
Session [ " Currentlanguage " ] = New Cultureinfo (language );
Return Redirect ( " Index " );
}

Public Actionresult about ()
{
Return View ();
}

Public Actionresult mobiletest ()
{
Return View ();
}

Public Actionresult mobiletest2 ()
{
Return View ();
}
}
}

The same function needs to be copied to a new asynchronous controller. Select the Controller folder, right-click it, and select "add → controller. New
The Controller is named commentfeedcontroller. The controller does not need the scaffolding template function. Select null from the drop-down menu.
Controller, and then press add.

This controller looks a little different from a typical controller. Using an asynchronous controller, a view is divided into two functions. Asynchronous execution of the first function
Request (for example, view retrieved ). The second function receives results, asynchronously calls and returns or displays the results.

Tip: In the following example, the local view is displayed. In some applications, it may be helpful to reduce network traffic and return a JSON result for JavaScript code to be processed and displayed. However, to simplify this example, focus on Asynchronous controllers, which will be used to return a partial view.

 Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. Web;
Using System. Web. MVC;
Using Mvcapplication. models;
Using System. Data. entity;
Namespace Mvcapplication. Controllers
{
Public Class Commentfeedcontroller: asynccontroller
{
Private Bookdbcontext DB = New Bookdbcontext ();
Public Void Commentsasync (Int Page)
{
Asyncmanager. outstandingoperations. increment ();
Asyncmanager. Sync () =>
{
VaR Bookcomments = dB. bookcomments. Include (
B => B. Book). orderbydescending (B =>
B. created). Skip (page * 3 ). Take ( 3 );
Asyncmanager. Parameters [ " Bookcomments " ] =
Bookcomments;
Asyncmanager. outstandingoperations. decrement ();
});
}
Public Actionresult commentscompleted (
Ienumerable <bookcomment> bookcomments)
{
Return Partialview (bookcomments );
}
}
}

The first function, commentsasync, receives the current page passed in from JavaScript and uses this value to retrieve the next three comments. Then, the comment is retrieved asynchronously and a variable is passed to the second function. The final task is to execute the asyncmanager. outstandingoperations. decrement () method. The increment (increment) and decrement matching of outstandingoperations (unsolved operations) is very important. Otherwise, when they do not match, the sync manager will cancel the request, which can organize the never-ending request.

The second function receives book comments and returns a partial view. This is the same as home/index view. The last step in this process is to create a partial view. Right-click the folder and add a new folder. This folder should be named "commentfeed" to match the Controller name. Select this folder, right-click, and clickAddViewName it comments ----- check the partial view before adding it.

@ Model ienumerable <  Mvcapplication  . Models. bookcomment  > 
@ Foreach (VAR item in Model ){
< H3 > < A Href = "@ URL. Action (" Details "," books ", new {ID = Item. Book. ID })" >
@ Html. displayfor (modelitem => item. Book. Title)
</ A > </ H3 >
< H4 > Comment posted: @ html. displayfor (
Modelitem => item. Created) </ H4 >
< P > @ Mvchtmlstring. Create (html. encode (item. Comment). Replace (
Environment. newline ," < BR /> ")) </ P >
}

 

The view above traverses comments, displays the title of the book and the link to the details page, creates the comment date, and creates the comment itself. Because the view may contain line breaks, use <br/> to replace each evironment. newline to match the comment input spacing.

 

For more information, see

Asynchronous Controllers

 


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.