Ajax. Net (learning data record 1)

Source: Internet
Author: User
Tags javascript array

Ajax. Net documentation (English) and website (English) are very useful for developers to get started quickly. Before introducing specific examples of using this technology, we will briefly review the core steps you need to know.

First from Ajax.. Net project website (English), download and decompress the Ajax file, and then follow your preferences in Visual Basic.. Net or C. net project, and then to Ajax. add a reference to the DLL file ). The only additional configuration step is to add the following in the <system. Web> element (located in the web. config file ):Code.

 
<Configuration>
<System. Web>
<Httphandlers>
<! -- Register the Ajax Handler -->
<Add verb = "post, get" Path = "ajax/*. ashx" type = "Ajax. pagehandlerfactory, Ajax"/>
</Httphandlers>
</System. Web>
</Configuration>

To make server-side functions available in Javascript, two things must be done. First, the function to be used must be marked with Ajax. ajaxmethodattribute. Second, during page loading events, you must call Ajax. Utility. registertypeforajax to register classes containing these functions. It seems complicated, but don't worry. In fact, you only need to add two more lines in the code. Let's look at an example.

// C # public class sample: system. Web. UI. Page {private void page_load (Object sender, system. eventargs E)
{// Register the server-side functions we are interested in
// Class
Ajax. Utility. registertypeforajax (typeof (sample ));
}
[Ajax. ajaxmethod ()]
Public String getmessageoftheday ()
{Return "experience is the mother of wisdom ";}
}
'Vb. net public class sample inherits system. Web. UI. Page
Private sub page_load (sender asobject, e as eventargs)
Handles mybase. Load
'Register the server-side functions that we are interested in
'Ajax. Utility. registertypeforajax (GetType (sample ))
End sub
<Ajax. ajaxmethod ()> _
Public Function getmessageoftheday () as string
Return "experience is the mother of wisdom"
End Function
End Class

The above example first tells Ajax. Net to find a friendly Ajax method in the sample class. It is exactly the same class as the actual page, but it can be any. Net class, or multiple classes can be registered. Ajax. Net then browses the specified class to find all the methods marked with ajaxmethodattribute. The sample class has a getmessageoftheday.

After that, the only thing you have to do is to use it in JavaScript. Ajax. net automatically creates a javascript variable with the same name as the registered class (sample in this example). It provides a function with the same name as ajaxmethod (getmessageoftheday in this example ). As shown below.

 
<Script language = "JavaScript">
Sample. getmessageoftheday (getmessageoftheday_callback );
Function getmessageoftheday_callback (response)
{Alert (response. Value );}
</SCRIPT>

In addition to the Javascript callback function, JavaScript getmessageoftheday also needs to have the same parameters (in this case, there are no parameters) as the corresponding part of the server, so that the execution and response can be passed at the completion. Here, we can see the asynchronous feature of Ajax at work, because the call to getmessageoftheday does not impede the execution of other JavaScript code, nor does it prevent the user from continuing operations on the page. When processing on the server side, Ajax. Net calls the specified callback function getmessageoftheday_callback and sends a response composed of the return values on the server side.

The ing between server-side code and JavaScript code may be messy. Figure 1 briefly shows the server-side code and JavaScript code, and the ing between them.

Figure 1: ing between server-side code and JavaScript code

Of course, there are more interesting Ajax. Net content worth introducing, such as support for. net types and rich callback responses (it is not just a value ). The following examples will focus on some features and help you understand how Ajax helps you create a successful application.Program.

Example 1: drop-down list of links

At the beginning of this article, we briefly discuss two traditional methods used to link two dropdownlists. When the selected index changes, return to the page; or load all possible data to the Javascript array and display it dynamically. We hope you can see how AJAX can replace these two solutions.

First, let's take a look at our data interface and use the data interface driver example. Our data access layer provides two methods: the first method is to retrieve the list of countries/regions supported by the system, the second method gets the country ID and returns the list of States/provinces. Because this is pure data access, we only need to use this method.

 
// C # public static datatable getshippingcountries ();
Public static dataview getcountrystates (INT countryID );
'Vb. net public shared function getshippingcountries () as datatable
Public shared function getcountrystates (byval countryID as integer) as dataview

Now, let's go to the opposite side and create a simple web form.

<Asp: dropdownlist id = "countries" runat = "server"/>
<Asp: dropdownlist id = "States" runat = "server"/>
<Asp: button id = "Submit" runat = "server" text = "Submit"/>

The page_load event is as simple as the preceding web form. We use the data access layer to retrieve available countries/regions and bind them to countriesdropdownlist.

 
// C # If (! Page. ispostback)
{
Countries. datasource = Dal. getshippingcountries ();
Countries. datatextfield = "country ";
Countries. datavaluefield = "ID ";
Countries. databind ();
Countries. Items. insert (0, new listitem ("Please select", "0 "));
}

Generally, the Code ends here. First, we will create the server-side function to be called from JavaScript.

 
'Vb. Net <Ajax. ajaxmethod ()> _
Public Function getstates (byval countryID as integer) as dataview
Return Dal. getcountrystates (countryID)
End Function

This is the same as any other function you normally use: it requires the ID of the country/region we want to obtain and passes the request to the Dal. The only difference is that we have used ajaxmethodattribute to mark this method. The remaining server step is to call registertypeforajax to use Ajax. Net to register a class that contains the preceding method (in this case, the following code is used ).

 
// C # Ajax. Utility. registertypeforajax (typeof (sample ));
'Vb. Net Ajax. Utility. registertypeforajax (GetType (sample ))

We have basically completed the process. The rest is to call the getstates method and process the response from JavaScript. When you select a new item from the country/region list, we want to call getstates logically. To this end, we will trigger the Javascript onchange event. In this way, our web form code is slightly changed.

 
<Asp: dropdownlist onchange = "loadstates (this)" id = "countries" runat = "server"/>

The javascript loadstates function is responsible for sending asynchronous requests through the proxy created by Ajax. net. Remember that by default, the proxy format created by Ajax. NET is <registeredtypename>. <serversidemethodname>. In our example, it will be sample. getstates. We also want to input the country/region ID parameter and the callback function that AJAX. NET should call after the server function is completed.

// JavaScript function loadstates (countries)
{
VaR countryID = countries. Options [Countries. selectedindex]. value;
Sample. getstates (countryID, loadstates_callback );
}

The last step is to process the response in our loadstates_callback function. The most useful feature of Ajax. NET is probably that it supports many. Net types (I have mentioned this many times ). Review the server functions returned by dataview. What does JavaScript know about dataview? I don't know anything, but Javascript is an object-oriented language. Besides, Ajax. Net can not only create objects similar to. Net dataview, but also map the values returned by this function to JavaScript copies. You should remember that JavaScript dataview is only a copy of the actual dataview. At present, it does not support other functions (for example, the rowfilter or sort attribute setting function) except for the ability to traverse rows and access column values ).

Function loadstates_callback (response)
{// If the server code is abnormal
If (response. Error! = NULL)
{// We should be able to do better alert (response. Error); return ;}
VaR States = response. value;
// If it is not the response we want
If (States = NULL | typeof (States )! = "Object ")
{Return ;}
// Obtain the state drop-down list var stateslist = Document. getelementbyid ("States ");
Stateslist. Options. Length = 0;
// Reset the state drop-down list
// Remember, its length is not the length in Javascript
For (VAR I = 0; I <states. length; ++ I)
{// Publish the columns of a row like the naming attribute
Stateslist. Options [stateslist. Options. Length] = New Option (States [I]. State, states [I]. ID );
}
}

After some error checks, the preceding JavaScript will get the state drop-down list, traverse the response value, and dynamically Add the options to the drop-down list. The code is clear, simple, and very similar to C # and Visual Basic. net. Personally (developers who have created JavaScript arrays and linked them together as server-side variables), I still need some time to believe that it actually works.

There is a major problem that may not be obvious. Because dropdownlist is dynamically created in Javascript, its items do not belong to viewstate and are not maintained. This means that the onclick event handler of the button needs to make some additional modifications.

'Vb. net
Private sub submit_click (sender as object, e as eventargs)
Dim selectedstateid as string = request. Form (States. uniqueid)
'Some user verification should be performed...
States. datasource = Dal. getcountrystates (convert. toint32 (countries. selectedindex ))
States. datatextfield = "state"
States. datavaluefield = "ID" states. databind ()
States. selectedindex = states. Items. indexof (States. Items. findbyvalue (selectedstateid ))
End sub

First, we must use request. form instead of the States. selectedvalue attribute. Second, if we want to re-display the list to users, we need to re-use the same data access method to bind the State dropdownlist. Finally, you must set the selected value programmatically.

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.