When writing server controls, you often need to send a large number of clients to the page. Code . In general, we can directly use output. Write () to write to the page, but this will bring about several problems:
1. If there are several such server controls on the same page, will the same client code be written to the client several times?
2. If you want the page to automatically run the corresponding client script?
In fact, solutions are provided in ASP. NET.
There are several methods in the page class:
Registerclientscriptblock The client code block can be sent to the page (of course, it can be not just a script or other text). This code will be written to the start part of the form.
Isclientscriptblockregistered Determine a specific segment based on a page-level key Registerclientscriptblock Whether the client code sent has been sent to the client.
Registerstartupscript The client code block can be sent to the page, which is written to the end part of the form. In this way, you can write a piece of automatically Running code after the page is loaded, just like the name.
Isstartupscriptregistered Determine whether the client code sent by registerstartupscript has been sent to the client based on a page-level key.
The above two methods can solve the above two problems.
Example:
//Generate client scripts
Private StringGetclientscript ()
{
Return@ "<Script language =" "JavaScript" ">
Function clientfunction ()
{
Implementation
}
</SCRIPT> ";
}
//Generate automatic client scripts
Private StringGetclientstartupscript ()
{
Return@ "<Script language =" "JavaScript" ">
Implementation
</SCRIPT> ";
}
//Add a client script to the pre-rendering event
Protected Override VoidOnprerender (eventargs E)
{
If(! Page. isclientscriptblockregistered ("clientscriptkey1 "))
Page. registerclientscriptblock ("clientscriptkey1", getclientscript ());
Page. registerstartupscript ("clientscriptkey2", getclientstartupscript ());
Base. Onprerender (E );
}
ToolTips:
The client script registration to the page must be completed in the pre-presentation. If it is done in redner, it will not start.
When writing a large client script, you can add @ to the front of the text. In this way, the code-changing sequence of the character generator will be "not" processed, so that the string can be easily written. If you want to include a double quotation mark in the character generator, use two pairs of double quotation marks.