Client script in asp.net 2.0

Source: Internet
Author: User
Tags eval resource tostring
asp.net| Script | When using ASP.net, we still need to use client script in many cases. The following is the author according to their own experience and some superficial research, to make a brief summary.

 First, write scripts directly in HTML

This is the easiest way to do it, until now when I write a Web page it's almost the most used one. Maybe some people who often use RegisterClientScriptBlock think this method is old-fashioned, but in my opinion, it can reduce the compilation time, but it can reduce the amount of code, readability is better, may also avoid some potential errors.

In some cases, however, writing directly is difficult to achieve, for example, when the script relies on the controls we generate dynamically in our code, we must use the Register method.

Writing scripts using the Literal control

The Literal control is basically writing a piece of text or code, so of course you can write client script, essentially the same method as the first method. In my own case, this method is usually used on write controls. Imagine a situation where we need to determine whether a batch of controls with client-side scripting events is displayed, and of course we can use a container such as a Panel, but most of these containers have a div or something, if in some case we don't want the div to appear? Of course, there may be a better and more beautiful way, but I simply use a Literal. '

Iii. using the Register Script function

In ASP.net 1.x, the Page class provides RegisterClientScriptBlock, Registeronsubmitstatement, and RegisterStartupScript functions so that you can do it in code ClientScript binding. However, in ASP.net 2.0, the functions Shitong moved to a ClientScriptManager class and a similar registerclientscriptinclude function was added. When using this class, we can access it through page.clientscript. Here are some of the different functions.

RegisterClientScriptBlock: This function adds clientscript to the top of the page, usually in the place immediately following the <form> tag. It should be noted that the script in this function may not be able to call the elements in the page correctly when it is written to the page or even executed, and the other elements of the page might not be loaded yet. A common application of this function is some client-side event handlers.

RegisterClientScriptInclude: This function is asp.net 2.0 new, it is generally used to put an external clientscript file, such as a. js file chain to access the page. In addition, it is basically the same as RegisterClientScriptBlock, including matters needing attention.

RegisterStartupScript: This function adds clientscript to the bottom of the page, and the benefit is that the reference to the page element can be handled correctly. Note that the script here will be executed before the OnLoad event on the page. In general, the code here is executed at once. The most common, for example, is to pop a message balloon after the page is loaded, or in a framed page, to update another page after a page has been loaded.

Registeronsubmitstatement: This function binds the ClientScript to the onsubmit event.

In general, after defining the event handler using RegisterClientScriptBlock, we can associate the function with the control using the following code, assuming we have defined a Confirmdelete function:

1string script = @ "return confirmdelete ();";
2btndelete.attributes.add ("onclick", script);

Iv. about Registerclientscriptresource

In addition to the four functions mentioned in the previous section, ASP.net 2.0 also adds a Registerclientscriptresource function. The difference between this function and the previous one is that it joins a script that is compiled into resources. Like the following line

1page.clientscript.registerclientscriptresource (this. GetType (), "script_resource.js");

The script_resource.js must be compiled into assembly on the server side by adding the following line to the server-side code

1[assembly:webresource ("Script_resource.js", "Application/x-javascript")]

After that, in the resulting page, we can see code similar to the following (in order to save the layout, I cut the length of D and T):

1<script src= "/webclient/webresource.axd?d=oz35v30&t=63204" type= "Text/javascript" ></script>

Here the WebResource.axd request is sent to the server and processed by a specific Axd HttpHandler to obtain the relevant resources (this is the Script-resource.js file). As we can see later, the technology has a wider range of applications.

V. Getpostbackclienthyperlink and GetPostBackEventReference

Both functions can get a string that can be used as a client to submit postback to the server. The use of the two is the same in general, the main difference being that the string returned by the former begins with "javascript:" and the latter does not. Look at the following examples:

1ClientScriptManager cs = Page.clientscript;
2btndelete2.attributes.add ("onclick", CS. GetPostBackEventReference (Btndelete, btnDelete2.ID.ToString ());
3linkdelete.href = cs. Getpostbackclienthyperlink (Btndelete, linkDelete.ID.ToString ());

Look at this piece of code generated by the relevant HTML source:

1<input name= "btnDelete2" type= button "id=" BtnDelete2 "value=" Delete2 "onclick=" __dopostback (' btndelete ', ' BtnDelete2 ') "/>
2<a href= "Javascript:__dopostback (' btndelete ', ' Linkdelete ')" id= "Linkdelete" >Delete</a>

From this example we can see the use of two functions, for the hyperlinked HRef, should use Getpostbackclienthyperlink, otherwise the browser may not execute correctly.

Vi. triggering server-side events via client

In some cases, we need to trigger the server event through the client's events. For example, we want to add a detection to the onchange event in a TextBox, which triggers a Btngo server event if the user enters a carriage return. (And, of course, we can do it entirely in JavaScript, for example). Can you do that? Here's a piece of code:

1string Scommand = Page.ClientScript.GetPostBackClientHyperlink (Btngo, "");
2string script = @ "Javascript:keyclick" ("Eval_command" ")";
3script = script. Replace ("Eval_command", strcommand);
4txtsearch.attributes.add ("onkeydown", script);

The following related JavaScript code:

1public Partial class CallbackPage:System.Web.UI.ICallbackEventHandler

This interface is ASP.net 2.0 new to join. Next we're going to implement its two-member approach (in my native MSDN, there are some places where the member methods of this interface do not match the actual members, such as the return type of raisecallbackevent into string and no GetCallbackResult method, I guess it was written early, but then there is no update, we look at the time to note:

1public int ncount = 0;
2
3public void RaiseCallbackEvent (String eventargument)
4{
5 ncount = Convert.ToInt32 (eventargument) + 1;
6}
7
8public string GetCallbackResult ()
9{
Ten return ncount.tostring ();
11}

let's write a method that receives the callback function, written in javascript:

1function Receiveserverdata (rvalue, context)
2{
3 Labelresult.innertext = rvalue;
4}

OK, then we need to link the Callback to the page and note that the key parts are here:

1void Page_Load (object sender, EventArgs e)
2{
3 ClientScriptManager cs = Page.clientscript;
4 String cbreference = cs. GetCallbackEventReference (This, "Arg", "receiveserverdata", "context");
5 String callbackscript = "function CallServer (arg, context) {" + Cbreference + ";}";
6 cs. RegisterClientScriptBlock (this. GetType (), "CallServer", Callbackscript, True);
7}

Finally, you need to write a good place to call:

1<input type= "button" value= "Testcallback" onclick= "CallServer" (Value, alert (' Data increment! ')] "/>

The value here is the incremental data that needs to be implemented. Note that the increment process is done within the RaiseCallbackEvent function, which is equivalent to the AjaxMethodAttribute function added to the Ajax. Run the test and we can see that there are no refreshing pages like Ajax that are actually implemented!

Looking at the generated HTML source code, we can see a line of JavaScript script resource links and a request for "WebResource.axd?" followed by a string of arguments, as previously mentioned Registerclientscriptresource produces the same result. You can also see that the page finally has a section generated with RegisterStartupScript:

1<script type= "Text/javascript" ><!--
2webform_initcallback ();//-->
3</script>

The CallServer function is expanded to resemble the following:

1function CallServer (ARG, context)
2{
3 Webform_docallback (' __page ', Arg,receiveserverdata, "", Null,false);
4}

The Webform_initcallback and Webform_docallback here are obviously in the JavaScript file generated by Webrequest.axd's request, if we are playing from temporary Internet files Open it, you can see the implementation of these two functions, a careful study, can be found that it is still used XMLHttpRequest and IFrame to achieve. Friends who are interested, go and study.

1function Keyclick (CMD)
2{
3 if (Event.keycode = 13) {
4 eval (cmd);
5}
6}

Well, based on the previous Getpostbackclienthyperlink features, it's easy to infer the HTML source code generated by the first snippet:

<input type= "text" id= "Txtsearch" onkeydown= "Javascript:keyclick (" Javascript:__dopostback (' btnGo ', ') ");"/>

You can see that in the onkeydown handler function Keyclick of Txtsearch, Btngo's server-side events are invoked again through the Eval function to trigger the postback by the client event. Is it something wonderful?

The Ajax in the asp.net? --Client Callback

Ajax technology makes many old Web apps look unwieldy because of their lack of refreshed page updates. And we know that a lot of Ajax is actually xmlhttprequest or a xmlrequestframe to achieve, and these two IE has long been supported. So does Microsoft offer an implementation that is based on or similar to Ajax? I know there's been a atalas recently, but in addition, there's already a way to achieve similar functionality in ASP.net 2.0.

First, we have to get the page to inherit from the ICallbackEventHandler interface. The method can have two kinds, corresponding to the Code-inside and Code-behind modes:

1<%@ Implements interface= "System.Web.UI.ICallbackEventHandler"%>


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.