ASP. NET client-side script FAQ (FRM. Attribute. Add)

Source: Internet
Author: User
Tags closing tag
Http://www.eggheadcafe.com/articles/20041016.asp

We have a fair amount of forum questions here on eggheadcafe.com that center around the areaClient-side scriptingWith ASP. net, and we thought it wocould be about time to start an FAQ article on the subject. we'll include all the basics of client-side script with ASP. net here, drawn from reliable sources (and simplified !) Along with our own "Discoveries ". we'll also insert links to other resources where appropriate. this is a community "Work in Progress" which we will add to on a regular basis, so please feel free to take advantage of the little "Article Discussion Forum" at the bottom to post or answer questions and make requests, as well as to make repeat visits to see "What's New" on the page! All contributions are encouraged, either via the discussion at the bottom of this page, or via email.

Basic concepts:

there are two important component parts of any ASP. net "page"-the ". aspx " portion, which is really a modified HTML page that holds the ASP: Control Server tags, client script, and HTML elements, and the "codebehind" or server-side portion of the page, which can be either inside

The script that shows up in the browser-rendered version of the page, however, cocould be generated by either having it prewritten, sitting inside <SCRIPT> </SCRIPT> tags in the aspx portion (or with a src = <scriptlocation> attribute), or it cocould be generated from server side processing, as we will soon see.

ASP. NET intrinsic client-script related methods

ASP. NET has several built in methods of the page class that were specifically designed to help with client-side scripting. Let's look at these first:

Registerclientscriptblock And Registerstartupscript Methods of the page class. These methods identify your script with a string key, so that multiple server control instances can request the script block without it being inserted in the output more than once. Isclientscriptblockregistered And Isstartupscriptregistered Methods of the page object are used to determine if the script has already been registered.

Differences between registerclientscriptblock and registerstartupscript

The registerclientscriptblock method inserts the client-side script immediately below the opening tag of the page object's <form runat =? Server?> Element. The registerstartupscript method inserts the specified client-side script just before the closing tag of the page object's <form runat =? Server?> Element. you need to include the <SCRIPT> start and end tags in the output when using the above methods. the choice of which method to use really depends on the "order" in which you want your script to be run by the browser when rendering the page.

Both of these methods take two strings as input. The second parameter,Script, Is the client-side script-including the Opening and Closing <SCRIPT> tags. The first parameter,Key, Serves as a unique identifier for the inserted client-side script.

There are two different methods for emitting client-side script because client-side script generally can have one of two purposes: code that is designed to run immediately when the page is loaded, and code that is designed to run when some client-side event occurs. an example of code designed to run when the page is loaded is script that sets the focus to a textbox. when you visit Google, a piece of client-side code is executed when the page is loaded to set the focus to the search textbox.

Registeronsubmitstatement Method

This method allows a page to access the clientOnsubmitEvent. The script shocould be a function call to client code registered elsewhere.Parameters:
KeyUnique key that identifies a script block.
ScriptThe client-side script to be sent to the client.

Example (this also usesRegisterhiddenfieldMethod ):

Void page_load (Object sender, eventargs E)
{
String scriptstring = "<script language = JavaScript> function doclick () {"; scriptstring + = "document. write ('<H4>' + myform. myhiddenfield. value + '</H4>') ;}< ";
Scriptstring + = "/" + "script> ";
Registerhiddenfield ("myhiddenfield", "Welcome to Microsoft. NET! ");
Registeronsubmitstatement ("Submit", "document. Write ('<H4> submit button clicked. </H4>')"); registerstartupscript ("Startup", scriptstring );
}

Preventing form submissions with client script

The confirm dialog box is displayed using the scriptConfirm (Message)Function. It displays a dialog box with the text specified byMessageInput parameter along with OK and cancel buttons.Confirm (Message)Function returns true if the user clicks OK and false if they click Cancel.

Confirm dialog boxes are normally used to ensure that the user wants to continue before submitting a form. when an HTML element is clicked to submit a form, if it fires a client-side event handler that returns false,The form submission is canceled. Typical usage in a web page as follows:

<Form...>
<Input type = "Submit" value = "click to submit" onclick = "Return confirm ('Are you sure you want to submit this form? '); "/> </Form>

When the user clicks the "click to submit" button, they see the confirm dialog. If the user clicks OK,Confirm ()Will return true and the form will be submitted. If, however, they click Cancel,Confirm ()Will return false and the form's submission will be canceled.

Code such as the above can be easily attached to the button that submits a form as follows:

Private void page_load (Object sender, system. eventargs E)
{
String scr = "Return confirm ('Are you sure you want to submit this form? ');";
This. button1.attributes. Add ("onclick", Scr );
}

Preventing form submissions that programmatically call _ dopostback

Listening for form. onsubmit (by using page. registeronsubmitstatement) is not sufficient because it won't fire when the form is submitted programmatically as with ASP. net's _ dopostback method. here is a solution that "hijacks" the _ dopostback method to ensure that your onsubmit handler is executed first:

In the aspx portion of your page:

<HTML>
<Head>
<SCRIPT>
// Save a reference to the original _ dopostback
VaR _ olddopostback = _ dopostback;
// Replace _ dopostback with another function
_ Dopostback = alwaysfirebeforeformsubmit;
Function alwaysfirebeforeformsubmit (eventtarget, eventargument ){
// Do whatever pre-form submission
// Chores you need here (example :)
Return confirm ('Are you sure? ');
// Finally, let the original _ dopostback do its work
Return _ olddopostback (eventtarget, eventargument );
}
</SCRIPT>

Then in your page_load:

Private void page_load (Object sender, system. eventargs E)
{
System. Web. UI. htmlcontrols. htmlform FRM = (system. Web. UI. htmlcontrols. htmlform) This. findcontrol ("form1 ");
FRM. Attributes. Add ("onsubmit", "alwaysfirebeforeformsubmit ();");
}

Validaterequest Directive

ASP. NET 1.1 will not allow HTML code to be sent to the server unless you use the page directive validaterequest = "false ". this can also be set globally in web. config in the pages element:

Add the "pages" line within the pre-existing <system. Web> tag:
 <System. Web>
<Pages validaterequest = "false"/>
</System. Web>

Note: If you use the above, your site may be vulnerable to cross-site scripting attacks, unless your code was already well-written to prevent that.

Getpostbackclientevent Method

The getpostbackclientevent method returns a string containing the client-side script for the PostBack event of a given control:

Parameters:
Control-the control that shoshould be passed to the PostBack method on the client side as the source of the PostBack event.
Argument-the argument that will be passed to the PostBack Method

String = getpostbackclientevent (control, argument)

Getpostbackclienthyperlink Method

The getpostbackclienthyperlink method returns a string representing a hyperlink to the client-side script call that initiates the PostBack process.

Parameters:
Control-the control that shoshould be passed to the PostBack method on the client side as the source of the PostBack event.
Argument-the argument that will be passed to the PostBack Method

This method allows developers to create hyperlinks that will cause the page to PostBack to the server. For example:

<A id = "link1" href = "<% = getpostbackclienthyperlink (button1," Submit ") %>"> link 1 </a>

The above creates a link to the PostBack method associated with the control with ID "button1", and passes in an argument of "Submit ".

The getpostbackeventreference Method

Gets a reference to the client-side function that initiates the PostBack. when building Web pages, it can be helpful to get a reference to the PostBack Script Function in order to programmatically cause the page to PostBack. this method will cause the page to PostBack, indicating that the specified control caused the PostBack.

String = getpostbackeventreference (control, [argument])

Parameters:
Control-the control that shoshould be passed to the PostBack method on the client side as the source of the PostBack event.
Argument-the argument that will be passed to the PostBack Method

The registerarraydeclaration Method

This method creates a client-side script block that declares an array. in addition, you can add an element to the array. subsequent callto this method using the same array name add new elements to the same array. in this way, multiple controls in a page request can add themselves or elements of their content to this array.

Void registerarraydeclaration (arrayname, value)

Parameters:

Arrayname (string)-the name to give to the client script array variable
Value (string)-the value to be added to the array. Can be the name of an object or control on the page.

Example:

Registerarraydeclaration ("textboxes", "textbox1 ")
Registerarraydeclaration ("textboxes", "textbox2 ")

Client-side output of the above two CILS wowould look like this:

<Script language = "JavaScript">
<! --
VaR textboxes = new array (textbox1, textbox2 );
// -->
</SCRIPT>

Causing a page to reload via server-side action:

// Cause page to reload from server-side response object:
Response. Write ("<SCRIPT> window. Location. Reload (true); </SCRIPT> ");

// Cause page to repeatedly reload
Response. Write ("<SCRIPT> window. setTimeout (" window. Location. Reload (true) ", 1000); </SCRIPT> ");

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.