ASP. NET client-server interaction

Source: Internet
Author: User
Tags first string
Http://www.tgreer.com/aspnet_html_03.html
ASP. NET client-server interaction

"Halt app until JavaScript confirm dialog clicked". "javascript in code-behind problem". "How to fire ASP. NET code from JavaScript function". "Confirm Delete ".These are all titles of recent questions posted in varous. Net forums around the Web. In each case, the question poser had a fundamental misunderstanding of the client-server nature of ASP. NET.

Asp. net is a Web programming language. the Web is based on the request-response model. the client makes a request, and the server generates a response. in the above examples, the coders had failed to keep this in mind, and so major confusion ensued. in a web application, code can run on the client, via JavaScript, or on the server, via C # Or VB. net code-behind. ASP. net confuses the issue by making it appear that server code is running in response to client actions (which isn't true; server code only runs in response to a form submit ). so it seems natural that, for example, a code-behind function cocould make an "alert" or "Please confirm" dialog appear in the browser, wait for a response, and then continue running the server code.

This article will offer some techniques for common issues with ASP. NET client-server interaction. It wocould be helpful to review my other two articles,ASP. NET and HTMLAndASP. NET viewstateFor background on ASP. NET.

Display a "thank you" Message

After a page is submitted and processed, you may wish to display a javascript message. you may want to thank the user, or simply confirm that their information was correctly posted. or, you may have found a problem with the supplied data, and need to display a warning message. this scenario cocould be described as wanting a JavaScript "onLoad" script to run on PostBack, but not to run the first time the page loads.

For this situation, use the "registerstartupscript" method of the "page" class. For this example, we'll use the same sample application as in the previous articles:

Figure 1. Visual Studio. NET

We'll add some code to the button's server-side click event.

Example 1. vs. Net "html" view.
 
Private void button#click (Object sender, system. eventargs e) {page. registerstartupscript (@ "Startup", @ "<SCRIPT> alert ('thank you! '); </SCRIPT> ");}

The method takes two arguments, both strings. the first string is a "key ". it's just a name that you can use, server-side, to refer to the script (for example, with the "isstartupscriptregistered" method ). the second string is the script itself. note that you must include the script tags. this is because the registerstartupscript method is extremely simplistic. it adds the entire contents of the second string to the end of the page's form. if you fail to provide the script tags, you'll just end up displaying text or HTML.

While it is fine to think of this as "displaying an alert when the user clicks a button", That isn' t quite what is happening. for example, the button cocould display an alert through JavaScript, without ever making a trip back to the server.

A breakdown of what we're re really doing:[1]User requests a page[2]Server generates a page[3]User clicks a button[4]The page submits the form[5]The server "unwraps" the form data, HTTP headers, and viewstate data to generate the "button#click" Event[6]The event handler runs, which writes a script to the page[7]The page is served back to the user[8]The script runs, displaying our "Thank you! "Message. The key lesson is that we can author client-side scripts in response to events on the server.

Integrating a "Confirm" Dialog

Another common source of confusion is how best to integrate a client-side "Confirm" message with server-side form processing. put another way, how can you make a button or link run both a client event and, conditionally, a server event?

For example, the user clicks a button to delete a record from the database. you 've already written the server code and attached it to the button. ideally, though, you want to present a dialog box asking the user if they really want to delete this record. if they answer "yes", the browser shocould submit the page to the server, where the "delete" code will run. if they answer "no", then the form submission shocould be canceled.

First, a short tutorial on HTML forms and buttons. when a button is clicked, it generates a "click" event. what happens when the button is clicked depends on what is defined in the button's "onclick" handler. consider this simple example:

Example 2. html button "onclick"
 
<Input type = "button" value = "Click me! "Onclick =" alert ('You clicked me. '); "/>

In the above example, the code to handle the click event is directly encoded, inline. however, it cocould also be contained in a JavaScript function, in which case our onclick handler wowould need to call the function, like so:Onclick = "myfunction ();".

One key characteristic of HTML buttons is that the click event's function can be canceled, if the function returns a "false" Boolean.

Example 3. html button "onclick" with "false" Boolean
 
<Input type = "button" value = "Click me! "Onclick =" return; alert ('You clicked me. '); "/>

Clicking this version of our button does nothing. this is because the onclick handler "returns", before any other code runs. the rest of the code is still tively "canceled" by the return. optionally, the "return" keyword cocould pass back a Boolean. if the Boolean is "false", the button's default action is canceled. this doesn't make much sense in the case of regular buttons. but in our scenario, we're not dealing with a regular button. we're re dealing with a submit button. returning a "false" wocould cancel the form submission. let's put the pieces together. consider the following code:

Example 4. cancelling a form submit
<HTML>  

Hopefully you can see that this form will never submit.

Javascript confirm () and ASP. NET

it wocould be tempting then, to write a JavaScript function that displays a confirm, and if the user clicks "yes", return "true ". if they click "no", return "false ". then we 'd add an "onclick" handler to our button, and we're in business. that's almost right. remember that an ASP. NET Server Control is not HTML. it produces, or emits, HTML. if we add an "onclick" handler to an ASP button Server Control, Asp. net assumes we're adding a server-side event handler, not a client-side event handler.

Let's look at our sample project in Visual Studio's "html" View (reformatted slightly to fit this article's stylesheet ). you can see that I 've already added the "Confirm" script. near the bottom, you'll see our button Server Control. if we tried to addOnclick = "Return confirmdelete ();"To the button Declaration, we 'd get errors when we tried to run the project. Why? Because an ASP. net button Server Control's "onclick" attribute expects you to provide a server-side function. this button isn' t an HTML submit button. it produces an HTML submit button when it runs.

Example 5. ASP. NET webform "html" View
<% @ Page Language = "C #" codebehind = "webform1.aspx. cs" autoeventwireup = "false" inherits = "testsuite. webform1" enableviewstate = "true" %> <! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en"> <HTML> 

What we have to do is add the client-side attribute to the button at run-time. we can do this by using the "add" method of the control's "attributes" collection.

Example 6. Adding an "onclick" in code-behind
Using system; using system. collections; using system. componentmodel; using system. data; using system. drawing; using system. web; using system. web. sessionstate; using system. web. ui; using system. web. UI. webcontrols; using system. web. UI. htmlcontrols; using system. text; using system. io; namespace testsuite {/// /// Summary description for webform1 ./// Public class webform1: system. web. UI. page {protected system. web. UI. webcontrols. textbox textbox1; protected system. web. UI. webcontrols. label label1; protected system. web. UI. webcontrols. button button1; private void page_load (Object sender, system. eventargs e) {// put user code to initialize the page here button1.attributes. add ("onclick", "Return confirmdelete ();") ;}# region web form designer generated code override protected void oninit (eventargs e) {// codegen: this call is required by the ASP. net web form designer. // initializecomponent (); base. oninit (E );}/// /// Required method for designer support-do not modify // the contents of this method with the code editor ./// Private void initializecomponent () {This. button1.click + = new system. eventhandler (this. button#click); this. load + = new system. eventhandler (this. page_load) ;}# endregion private void button#click (Object sender, system. eventargs e) {page. registerstartupscript (@ "Startup", @ "<SCRIPT> alert ('record deleted. '); </SCRIPT> ");}}}

Live example of this project:ASP. NET confirm Project

Conclusion

ASP. net is a powerful server-side web development language. however, it's very nature can make it somewhat challenging to integrate client-side code. this article demonstrated two techniques for integrating client-side scripts into an ASP. NET application.

About the author

Thomas D. greer has over 12 years experience in the printing business. he held the position of Director of Development for your lidated graphics, where he wrote the coin ecommerce platform. prior to that he was vice-president of technology of a large printing company acquired by using lidated graphics, where he was responsible for the development of a completely custom-written plant management system still in use.

Today Thomas provides consulting, development, implementation, and training services to your cial printers. He can be reached on the webWww.tgreer.com.

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.