Use Ajax. Net in static pages to implement refreshing pages

Source: Internet
Author: User
I. Introduction

We know that the Asp.net ApplicationProgramThe fact is running on the server. User requests must be sent continuously to a remote server. After the server executes a local program, it reloads the page and then sends the client. So there is a problem of constant refreshing, and the page is constantly flashing. The user is not tired of it, the operation efficiency is also greatly reduced by 4, and the server load is increased. In fact, a client request only submits a new request to the Web server at a certain time to retrieve the response to user input. In this case, developers can use JavaScript to load all responses on the client to provide a better user experience. Unfortunately, in many cases, it is better not to return or load all responses to Javascript. Instead, it only returns the expected results and the execution process is still running on the server. Ajax provides a new intermediate choice that allows you to utilize server-based applications while maintaining timely response and flexibility.

Ajax relies on servers as intermediaries to distribute and process requests. To do this, the. NET encapsulation class depends on the client's request object, and the XMLHTTPRequest object is supported by most browsers. Therefore, using this object is a good solution.

Therefore, to achieve non-refresh pages, our client pages are made static pages. The static page calls the. NET class method through ajax.net. This is the most concise and efficient solution.

Ii. How to Apply ajax.net

1. Introduce the Ajax. dll file in the project.

Ajax. dll is a class library file developed by Microsoft on ASP.net. This class library encapsulates the implementation details of the XMLHttpRequest request server and is a solution for Ajax knowledge application on the Asp.net platform. In the. NET project, add the reference to it, and then you can start to use the Ajax. dll package for development.

2. Set httphandle in Web. config

To make it work, the first step must be done on the web. install httphandle in config to set the encapsulation package. Instead of explaining in detail how httphandle works, we only need to know that they can be used to process Asp.net requests. For example, all objects are *. for aspx requests, you can use system. web. UI. the pagehandlerfactory class is sent to the control handle. Simply put, we send any code to Ajax /*. the request of ashx is sent to Ajax. the request processing handle of pagehandlerfactory.

3. Write Server Functions

Now we write server-side functions, which can be called asynchronously by the client. Although not all return types are supported now, we still insist on adding the server function. In the page class of the codebehind file, add the following method:

[Ajax. ajaxmethod ()]
Public int serversideadd (INT firstnumber, int secondnumber)
{
Return firstnumber + secondnumber;
}

Note that this function has the Ajax. ajaxmethod () custom attribute. The property service informs the Ajax encapsulation class to create a javascript proxy for this method so that it can be called by the client.

3. Application Instance (click to download the source code)

Our applications mainly operate databases. database data is displayed in tables on the page to add, delete, update, and query functions. What's more, it is a general example with extremely clever implementation methods. No page is refreshed andCodeVery delicate. The following describes how to implement these functions through Ajax technology.

· Create a project httpforajax and introduce the Ajax. dll file in your project.

· Add in your web. config.

<Httphandlers>
<Add verb = "post, get" Path = "ajax/*. ashx" type = "Ajax. pagehandlerfactory, Ajax"/>
</Httphandlers>

· Create your HTML page.

1. Add the HTML page infoclass.htm to the project. This page provides query, common tools, and data presentation functions.

The page mainly contains four Divs, one of which is the tree "divtree ". The query area is "divfindtable", and the toolbar is called
"Divtoolbar", one is the data zone called "divdatagrid. For example:

2. Add some references between

<SCRIPT src = JS/XML. js> </SCRIPT>
<Link href = "CSS/mystyle.css" type = "text/CSS" rel = "stylesheet">
<SCRIPT src = "/httpforajax/ajax/common. ashx" type = "text/JavaScript"> </SCRIPT>
<SCRIPT src = "/httpforajax/ajax/ttyu. ajaxdata, httpforajax. ashx" type = "text/JavaScript"> </SCRIPT>

Note: XML. JS is a client program written in JavaScript.

Mystyle.css is a style file.

Common. ashx is a public method used to call Ajax.

Httpforajax. ashx is the reference of the class we want to compile with Ajax below. Httpforajax is the project namespace.

Ttyu. ajaxdata is a self-developed class, where ttyu is the namespace and ajaxdata is the class name.

3. Use JavaScript to write scripts,

Function Init ()
{
Domtree = new dhtmlxtreeobject (document. getelementbyid ('divtree'), "100%", "100%", 0 );
Domtree. setimagepath ("IMGs /");
Domtree. enabledraganddrop (true)
Domtree. setdraghandler (mydraghandler );
Domtree. setonclickhandler (selecttreenode );
VaR S = ajaxdata. getxmltree (). value;

Domtree. loadxmlstring (s );
Domtree. openitem ("R_1 ");
Selecttreenode ("R_1 ");
Divtoolbar. innerhtml = ajaxdata. gettoolbartable (tablename). value;
Divdatagrid. innerhtml = gettableouterhtml (tablename );
}

The init method obtains the tree content through the getxmltree method of Ajax, and gettoolbartable obtains the content of the toolbar. Use the gettableouterhtml method to retrieve all data of the tinfoclass physical table and display it in the table.

Function find ()
{
VaR table = ajaxdata. getxmlfindtable ("grade name like '%" + txtname. Value + "% '");
Divdatagrid. innerhtml = table. value;
}

The query method find () is to query by grade name through the getxmlfindtable method of Ajax and display the result.

Function openaddweb ()
{
VaR retid = openaddwin ('infoclass _ edit. aspx? Isadd = true ', 370,300 );
If (retid =-1) return;
Insertrow (maid, retid );
}

Open the infoclass_edit.aspx page in the openaddweb method to add data on this page. If the returned value is not-1, it indicates that new data is added and the data is inserted into the last row of the table. Retid indicates the ID of the last row.

Function openeditweb (thiscell)
{
VaR id = thiscell. previussibling. previussibling. innertext;
VaR retid = openaddwin ("infoclass_edit.aspx? Id = "+ ID +" & isadd = false ", 370,300 );
If (retid =-1) return;
// Update rows exist.
VaR currrow = thiscell. parentelement
Setrowtext (currrow );
// Setrowtext (currrow, retdatarow );
}

The openeditweb method is to enable the infoclass_edit.aspx page after the user clicks a cell to edit the row of data on this page. If there is an update row, replace the content of the current row ..

· Create an Ajax class. (See the ajaxdata. CS file.) The namespace is ttyu and the class name is ajaxdata.

1. Define the static variable MDT. MDT is a data table object that reads data from a physical table and stores it in memory. Our main operations are completed by it. What is defined as static is that we do not want to access the database repeatedly. We read data at one time and use it permanently.

Static public datatable MDT;

2. Define our main method. Add [Ajax. ajaxmethod ()] to the upstream of each method.

// Obtain the table tablename data, which is returned as an XML string
[Ajax. ajaxmethod ()]
Public String gettableouterhtml (string tablename)
{
Datatable dt = dB. DB. getdatatable (tablename );
MDT = DT;
Return dB. gettableouterhtml (Dt. defaultview );
}

The gettableouterhtml method reads the physical table name to the memory and obtains the table in XML format through its view. Here we read and save it in MDT. This method is also used to present data by using the data table view.

// Obtain the table tablename data, which is returned as an XML string
[Ajax. ajaxmethod ()]
Public String getxmlfindtable (string rowfilter)
{
Datatable dt = MDT;
Dataview DV = DT. defaultview;
DV. rowfilter = rowfilter;
Return dB. gettableouterhtml (DV );
}

Getxmlfindtable is used to query data from MDT Based on query conditions and return the data to the client.

// Delete a row
[Ajax. ajaxmethod ()]
Public bool deleterow (string tablename, int ID)
{
String SQL = "delete from" + tablename + "where id =" + ID;
Bool issuccess = dB. DB. executesql (SQL );
If (issuccess)
{
Datarow DR = MDT. Select ("ID =" + id) [0];
MDT. Rows. Remove (DR );
}
Return issuccess;
}

Deleterow is a row that deletes a physical table and is also deleted synchronously in the MDT.

// Convert the data row into an array and return it
[Ajax. ajaxmethod ()]
Public object getdatarow (int iid)
{
Datarow DR = MDT. Select ("ID =" + IID) [0];
Return dr. itemarray; // The numeric type cannot be blank.
}
Getdatarow is a row from the memory table MDT that obtains the ID as IID and returns it to the client through arrays.
[Ajax. ajaxmethod ()]
Public String gettoolbartable (string tablename)
{
Return dB. gettoolbartable (tablename );
}

Gettoolbartable is the content organized as a toolbar and returned to the client.

· Create a business data class ttyupkdata. (See the ttyupkdata. CS file.) The namespace is ttyu and the class name is ttyupkdata.

This class has some common methods.

Public bool insertdatarow (datarow DR, int begincolumnindex) is used to insert the data row Dr into the physical table. begincolumnindex indicates that the columns from the beginning are inserted.

Public bool updatedatarow (datarow DR, int begincolumnindex, string filter) is used to update the data of the Data row Dr to the physical table, and begincolumnindex indicates the columns starting update. Filter indicates the row to be updated. Is a filtering condition.

Public String gettableouterhtml (dataview DV) is a common method for displaying a data view as a table. And define the style through class.

// get the table header and all data from a data view, and return the table string in XML format
Public String gettableouterhtml (dataview DV)
{< br> stringbuilder ret = new stringbuilder ();
ret. append ("












"); ret. append (" "); // Title foreach (system. data. datacolumn DC in DV. table. columns) {< br> If (DC. ordinal = 0) // hide the column ret. append (" "); else ret. append (" "); }< br> ret. append (" "); // The filtered data in the view foreach (datarowview DRV in DV) {< br> datarow DR = DRV. row; // DV. table. rows [I]; ret. append (getrowouterhtml (DR); }< br> ret. append ("
" + DC. columnname + "" + DC. columnname + "
");
return ret. tostring ();
}

· Create a page data editing class (see the file pageedit. CS) with the namespace ttyu. Web and the class name pageedit.

This class is a general method that implements unified processing of all the editing pages (including adding and modifying data) through inheritance techniques. Page does not require a line of code.

Conclusion

Ajax technology can provide a rich client experience, while ajax.net provides the possibility for you to easily implement such powerful functions. Static pages are not refreshed. Our static pages can be fully combined with Asp.net through Ajax. Use. Net to manage the background. The front-end is called through JavaScript. This perfect combination is the best way to solve the problem.

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.