Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

Wrox Professional Web Parts and Custom Controls with ASP.NET 2.0 phần 7 pptx
Nội dung xem thử
Mô tả chi tiết
Dynamically Generating Code
The next step up the evolutionary ladder of client-side code writing is to dynamically generate your code
and insert it into your page. The first step in generating dynamic client-side code is to prepare, in your
server-side code, the client-side code to be added to the page and concatenate it into a string variable.
The range of code that you can build is infinite, but I’ll stick to the simple SayHello example. This Visual
Basic 2005 example puts the SayHello program into a single string:
Dim strSayHello As String
strSayHello = “<script>function SayHello(){window.alert(“ & _
“‘Hello, World’);}</script>”
In C#:
string strSayHello;
strSayHello = “<script>function SayHello(){window.alert(“ +
“‘Hello, World’);}</script>”;
Even if your code is being generated dynamically, it’s often a good idea to write an initial, static version
of the code in the Source view of your page. This gives you all the IntelliSense support of the Visual
Studio 2005 editor plus some syntax checking. It’s also a good idea to do some testing with your static
code before cutting the code out of your page and incorporating it into your server-side code.
The next step is to add this routine to your page from your server-side code. The simplest way to do this
is to use the Response object’s Write method, as this Visual Basic 2005 version does:
Me.Page.Response.Write(strSayHello)
In C#:
this.Page.Response.Write(strSayHello);
However, there are two problems with this method. The first problem is that you have very little control
over where the client-side code is added. Used from the Page_Load event of a WebForm, for instance,
the script block is inserted ahead of the HTML and DOCTYPE tags that begin your Web page (the code
still executes in Internet Explorer, however).
Typically, there are two places where you want to put your script:
❑ At the head of the form, so that the code is guaranteed to have been processed by the browser
by the time the user works with the control that the code is associated with
❑ At the end of the form, so that the code can’t execute until all of the controls have been
successfully loaded
The second problem with using Reponse.Write to add your client-side code to the page is: How do you
prevent different copies of your control repeatedly adding the script block to the page? For instance, if
you create a control that adds client-side code, there is nothing stopping the developer using your control
from putting two or more copies of your control on the page that she is building. If both copies of your
control insert client-side code into the page, the results of executing the code are going to be difficult to
predict but almost certainly won’t be what you want.
253
Adding Advanced Functionality
15_57860x ch09.qxd 10/4/05 9:22 PM Page 253
The answer to this second problem is to treat the script block in a page as a “library” block: the block
contains a variety of useful routines that may be called from all the copies of the control on the page. All
you need to do is ensure that, after your library block is added to the page at least once and that no other
control adds the library again.
Both the problems of controlling the placement of your code and preventing code from being added several times are handled by the RegisterClientScriptBlock and the RegisterStartUpScript methods of the
ClientScriptManager object, which has methods for supporting most client-side scripting activities. You
can retrieve the ClientScriptManager for a page from the Page object’s ClientScript property.
The difference between the two methods is where the code is placed:
❑ RegisterClientScriptBlock puts the code immediately after the form open tag that starts the form
on your page.
❑ RegisterStartUpScript puts the code just before the form close tag that ends the form on your
page.
RegisterStartUpScript can be used to add script blocks that contain code that isn’t in routines — in
other words, code that executes as part of the page load process. Because the RegisterStartUpScript
code is placed at the end of the form, the controls on the form will have been loaded and be available for
processing from your client-side code. This makes RegisterStartUpScript a good choice to add any code
that you want to execute before the user has taken any action (such as code to position the cursor in
some field when the page is first displayed).
Both of the Register* methods accept four parameters:
❑ A system type: For this parameter you just need to pass the type of your custom control. This
parameter allows ASP.NET to keep scripts from different controls separate.
❑ The key for the script block: This key allows ASP.NET to check whether the script block has
already been added.
❑ The script itself: This parameter is concatenated into a single string.
❑ A Boolean value: A value that indicates, when True, that this script should be placed inside a
<script> element. If you set this parameter to False, you’ll need to include the <script> element
in your code. This parameter is optional and defaults to False.
If you are generating script blocks for constituent controls, you still want to pass the type of your custom control to the Register* event rather than your constituent controls. While your custom control is a
unique type, your constituent controls are more likely to be the relatively common TextBoxes, ListBoxes,
and other ASP.NET controls.
As you’ll see in this section, the Page’s ClientScriptManager object has a number
of methods that are useful when generating client-side code. In ASP.NET 1.x some of
the methods were available directly from the Page object (RegisterClientScriptBlock
and RegisterStartUpScript are two examples). However, those versions of the
methods are now marked as obsolete and you should use the versions available
from the ClientScriptManager object.
254
Chapter 9
15_57860x ch09.qxd 10/4/05 9:22 PM Page 254
This Visual Basic 2005 example places the code for the SayHello routine at the start of the form inside a
<script> element:
Dim csm As System.Web.UI.ClientScriptManager
csm = Me.Page.ClientScript
csm.RegisterClientScriptBlock(Me.GetType, “PHVBlock”, strSayHello, True)
In C#:
System.Web.UI.ClientScriptManager csm;
csm = this.Page.ClientScript;
csm.RegisterClientScriptBlock(this.GetType(), “PHVBlock”, strSayHello, true);
The resulting JavaScript code looks like this:
<script type=”text/javascript”>
<!--
function SayHello(){window.alert(‘Hello, World’);}// -->
</script>
When adding code to your page, you’ll frequently want to incorporate the name of your control into
your code. You can retrieve the name of your control at run time from your control’s UniqueId property,
as discussed in Chapter 3.
If you want your client-side code to manipulate the HTML structure that wraps a Web Part, see
Chapter 5 for a description of a Web Part’s HTML structure.
In addition to the ClientScript object’s RegisterClientScriptBlock and RegisterStartupScriptBlock, you
can also use the RegisterOnSubmitStatement to add code to your page. The RegisterOnSubmitStatement
adds a script block to your host page that isn’t tied to any particular control but executes just before the
page is posted back to the server. This Visual Basic 2005 example associates the SayHello routine with
the submit event of the page:
Dim csm As System.Web.UI.ClientScriptManager
csm = Me.Page.ClientScript
csm.RegisterOnSubmitStatement(“PHVSubmitBlock”, strSayHello)
In C#:
System.Web.UI.ClientScriptManager csm;
csm = this.Page.ClientScript;
csm.RegisterOnSubmitStatement(“PHVSubmitBlock”, strSayHello);
The key that you use when adding a script block allows you to check whether the block has already been
added by using the Page’s IsClientScriptBlockRegistered method (similar Is*Registered methods check for
the results of other Register* methods). Passed the key for a script block, the IsClientScriptBlockRegistered
method returns True if a client script block with that key has already been added to the page.
255
Adding Advanced Functionality
15_57860x ch09.qxd 10/4/05 9:22 PM Page 255
This Visual Basic 2005 code takes advantage of the method to avoid adding the SayHello routine if it’s
already been added:
Dim csm As System.Web.UI.ClientScriptManager
csm = Me.Page.ClientScript
If csm.IsClientScriptBlockRegistered(“PHVBlock”) = False Then
csm.RegisterClientScriptBlock(“PHVBlock”, strSayHello)
End If
In C#:
System.Web.UI.ClientScriptManager csm;
csm = this.Page.ClientScript;
if(csm.IsClientScriptBlockRegistered(“PHVBlock”) == false)
{
csm.RegisterClientScriptBlock(“PHVBlock”, strSayHello);
}
Four other notes on using the Register* methods:
❑ Using the Is*Registered methods is optional. The Register* methods don’t add anything if an
item with the same key has already been added (and no error will be raised).
❑ You must call the Register* methods before the Render method (that is, in the PreRender event
or earlier).
❑ All scripts added with any one of the Register methods go into the same <script> element. For
instance, all the script code added with the RegisterClientScriptBlock goes into the same <script>
element at the start of the form.
❑ The keys assigned in the RegisterClientScriptBlock, RegisterOnSubmitBlock, and
RegisterStartupScript are kept separate from each other. If you add a script block with the key
“PHVBlock” with RegisterClientScriptBlock, it won’t prevent adding a block with the same key
using one of the other Register* methods.
Support for Client-Side Script
ASP.NET provides several other tools to support client-side processing. The following subsections cover
these other tools.
Adding Arrays
While your server-side code has access to databases on your server, code executing in the browser does
not. The usual solution to this problem is to extract the data from the database in your server-side code
and embed that data in a static array in the client-side code. The RegisterArrayDeclaration method not
only adds the necessary array to the page, but also flags the array has being added. As a result, controls
that share data (for instance, a list of valid customer codes) can avoid adding the data twice.
256
Chapter 9
15_57860x ch09.qxd 10/4/05 9:22 PM Page 256