Using ASP. NET Ajax and jquery together to solve the problem of page turning Selection

Source: Internet
Author: User
1. Preface

In a development project, users are often asked to select data from the list. For example, users who are allowed to participate in an activity and provinces or regions that are allowed to participate in a project are usually selected. When the data volume is small, we can use any data binding control to display all the data and display the check box before each data item. However, it is not appropriate to display all the data when the data volume is large, we first consider using paging. However, after paging is used, the problem also arises. Some developers may use the server to maintain the selected project while switching pages.CodeWrite and save the data in the session. The biggest drawback of this method is that the data is submitted to the server every time, and the selected data only needs to be used on the current page, so it still occupies the session.

For this type of problem, we now have a better choice, using ASP. NET Ajax and jquery together to achieve paging selection.

2. Related Theories

Use ASP. in net Ajax, The scriptmanager and updatepanel controls allow you to easily implement the pagination of the gridview. Now, you need to consider making the check box selected based on your selection after the page ends. In fact, in Ajax. net, Microsoft provides us with full Ajax request lifecycle control. The following events will be triggered on the client:

    • Application. init -- triggered when a page is requested for the first time. This event is not triggered in asynchronous sending.
    • Pagerequestmanager. initializerequest -- triggered before an asynchronous request starts, which is equivalent to the pre-start phase.
    • Pagereqeustmanager. beginrequest -- triggered before an asynchronous request starts.
    • Pagerequestmanager. pageloading -- this event is triggered before the client receives the asynchronous request response from the server and updates updatepanel.
    • Pagerequestmanager. pageloaded -- this event is triggered when the client receives the asynchronous request response from the server and updates the content in updatepanel. This event is also triggered during page initialization and loading.
    • Application. Load -- this event is triggered during normal and asynchronous sending.
    • Pagerequestmanager. endrequest -- this event is triggered no matter whether an exception occurs after an asynchronous request is completed.
    • Application. Unload -- this event is triggered when the user leaves or reloads the page.

Through the above analysis, we only need to update the check boxes based on the selected status after the asynchronous paging request is complete. You can use the powerful selector in jquery to obtain the check box. For example, the following code Selects all the check boxes in a gridview.

 
$ ('Div [# <% = gdvcustom. clientid %>] input [type = checkbox]')

Based on the above analysis, the following sample code shows the final application result.

3. solution example

In this example, the northwind database is used to demonstrate the effect of selecting a customer (MERS MERs table.

3.1 create a solution and create an ASP. NET Website.

3.2 Create a JS directory under the website and copy the jquery script file to the directory.

3.3 access the database using LINQ to SQL. First, create the app_code directory on the website, create the northind. dbml file under the directory, use the server resource manager to create a connection to the database, and drag and drop the MERs table to the designer of the dbml file.

3.4 open the default. aspx page and switch to the design view. Drag and Drop the scriptmanager and updatepanel controls and rename them to smcustomer and upcustomer.

3.5 place the gridview control in updatepanel and rename it as gdvcustom. Use its shortcut tag to create a LINQ data source using northinwddatacontext and specify the table to be displayed as MERS MERs. Finally, delete unnecessary columns as needed, however, at least the customerid and contactname columns must be saved.

3.6 Add a check box to the template column in The gridview control and set its value and title attributes to the customer's ID and contact name respectively. In addition, to help users better understand the currently selected customers, add a list to the page. The HTML code in the form is as follows:

 <  Div  > <  ASP  :  Scriptmanager  ID = "Smcustom"  Runat  = "Server"> </  ASP  :  Scriptmanager  > <  ASP  :  Updatepanel  ID  = "Upcustom"  Runat  = "Server"> <  Contenttemplate  > <  ASP :  Gridview  ID  = "Gdvcustom"  Runat  = "Server"  Allowpaging  = "True"  Autogeneratecolumns  = "False"  Performanceid  = "Ldsnorthwind"  Width  = "100%"> <  Columns  > < ASP  :  Templatefield  Headertext  = "Select"> <  Itemtemplate  > <  Input  Type  = "Checkbox"  Value  ='  <% # Eval ("customerid ") %>  '  Title ='  <% # Eval ("contactname ") %>  '  Onclick  = 'Changeselect (this); '/> </  Itemtemplate  > </  ASP  :  Templatefield  > <  ASP  :  Boundfield Datafield  = "Customerid"  Headertext  = "Customerid"  Readonly  = "True"  Sortexpression  = "Customerid"/> <  ASP  :  Boundfield  Datafield  = "CompanyName"  Headertext  = "CompanyName"  Readonly = "True"  Sortexpression  = "CompanyName"/> <  ASP  :  Boundfield  Datafield  = "Contactname"  Headertext  = "Contactname"  Readonly  = "True"  Sortexpression  = "Contactname"/> <  ASP :  Boundfield  Datafield  = "Contacttitle"  Headertext  = "Contacttitle"  Readonly  = "True"  Sortexpression  = "Contacttitle"/> <  ASP  :  Boundfield  Datafield  = "Address"  Headertext = "Address"  Readonly  = "True"  Sortexpression  = "Address"/> </  Columns  > </  ASP  :  Gridview  > <  ASP  :  Linqdatasource  ID  = "Ldsnorthwind"  Runat = "Server"  Contexttypename  = "Northwinddatacontext"  Select  = "New (customerid, companyName, contactname, contacttitle, address )"  Tablename  = "Customers"> </  ASP  :  Linqdatasource  > </  Contenttemplate  > </  ASP  : Updatepanel  > <  H3  > Selected customer </  H3  > <  Select  Size  = "5"  ID  = "Selcustom"> </  Select  > <  Input  Type  = "Button" ID  = "Btnsave"  Value  = "Save"/> </  Div  > 

3.7 add jquery Script Reference first:

 
<ScriptType= "Text/JavaScript"SRC= "JS/jquery-1.3.2.js"> </Script>

3.8 After the Ajax request is complete, the Add script is displayed based on the check box selected by the user (note that the script must be placed below scritpmanager or some objects will be displayed as undefined ):

 <  Script Type  = "Text/JavaScript"> SYS. application. add_init (application_init ); Function Application_init (){ VaR PRM = SYS. webforms. pagerequestmanager. getinstance (); PRM. add_endrequest (prm_endrequest );} Function Prm_endrequest () {$ ( 'Div [# <% = gdvcustom. clientid %>] input [type = checkbox]' ). Each ( Function (){ VaR LST = $ ( '# Selcustom' ) [0]; VaR Contains = False ; VaR Imgindex =-1; For ( VaR I = 0; I <lst. Options. length; I ++ ){ If (Lst. Options [I]. value = This . Value) {contains = True ; Break ;}} If (Contains ){ This . Checked = True ;}});} </  Script  > 

3.9 after the script is loaded on the page, double-click and click events are processed for the corresponding list and button controls to remove the project and select the project:

$ ( Function () {$ ( '# Selcustom' ). Dblclick ( Function (){ VaR LST = This ; $ ( 'Div [# <% = gdvcustom. clientid %>] input [type = checkbox]' ). Each ( Function (){ If (This . Value = lst. Options [lst. selectedindex]. value) This . Checked = False ;}); This . Options. Remove ( This . Selectedindex) ;}); $ ( '# Btnsave' ). Click ( Function (){ VaR MERs = '[' ; VaR Count = 0; VaR LST = $ ('# Selcustom' ) [0]; For ( VaR I = 0; I <lst. Options. length; I ++) {customers + = lst. Options [I]. value; customers + = ',' ; Count ++ ;} If (Count> 0) {customers = customers. substr (0, customers. Length-1);} customers + = ']' ; Alert (customers );});});

3.10 compile the changeselect function to add or remove customers from the list box when you click the check box:

 Function Changeselect (chk ){ VaR LST = $ ('# Selcustom' ) [0]; VaR Contains = False ; VaR Cusindex =-1; For ( VaR I = 0; I <lst. Options. length; I ++ ){ If (Lst. Options [I]. value = chk. Value) {contains = True ; Cusindex = I; Break ;}} If (Contains) {lst. Options. Remove (cusindex );} Else { VaR Opt = Document. createelement ( "Option" ); Opt. Text = chk. Title; opt. value = chk. value; lst. Options. Add (OPT );}};

3.11 preview in the browser, as shown in the following figure:

 

4. Summary

ASP. net Ajax provides developers with convenient methods to implement asynchronous requests. Through scriptmanager and updatepanel, asynchronous requests can be implemented without writing any code, at the same time, the flexible selector provided by jquery can help us better control the page elements and combine the two to give full play to their respective advantages, A powerful ASP can be compiled while saving developers a lot of time.. NET application.

5. Problems

5.1 In this example, only the corresponding data is selected and saved to the Javascript array of the client. The complete function can be implemented only within the last mile. You can try to use jquery to complete Ajax requests, finally, the customer selection function is implemented.

5.2 In addition, there is a trap in this example. When setting an event for the check box in the table, jquery is not used, but the onclick event is used directly. This damages the original intention of jquery, if jquery is also used here to add an event to the check box using the selector after page loading is complete, is it OK?

5.3 can I encapsulate some copy and paste methods in Javascript in this example into common functions?

6. Reference
    • Stephen Walther. asp. net3.5 unleashed: Sams, 2007
    • Bear bibeault, Yehuda Katz. jquery in action. Chen Ning: People's post and telecommunications press, 2009

Source code download

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.