The .NET Framework 2.0 introduced many new feature that make JavaScript usage with ASP.NET pages easy. The ClientScriptManager class in the framework has many new useful methods that help developers use these features very effectively. In this first part of the series, Satheesh discusses some of the common scenarios to use the frequently used overload methods of the ClientScriptManager class. He starts with an overview of the ClientScriptManager class and then examines the RegisterClientScriptBlock, RegisterStartupScript, and RegisterOnSubmitStatement methods with the help of relevant source code, screenshots and usage instructions.

" /> Using JavaScript Effectively in ASP.NET 2.0 - 技术笔记 - 岁月留声QtAsp

岁月留声QtAsp

Qt in Linux , Asp Asp.net Jsp Php in Web

« 电脑系统设备管理器里看不到集成网卡"网络适配器"的项目Protecting Sections of your Web.Config File »

Using JavaScript Effectively in ASP.NET 2.0

Introduction

JavaScript is one of the very versatile scripting languages that are used in Web applications. Even though we can accomplish everything in server side programming using C#, we can still prefer to do some of the things, like validations, etc., using JavaScript. In ASP.NET 1.x, we do not have that much support in the framework to hook JavaScript functions from the asp.net page dynamically. This drawback was addressed with the release of ASP.NET 2.0 by providing developers a lot of features to embed JavaScript blocks dynamically through a class called ClientScriptManager. I have divided this article into 2 parts. Part 1 will deal with 3 different methods that are packed with ClientScriptManager class with examples, while the Part 2 will discuss the left out methods with some other useful JavaScript tips for ASP.NET.

ClientScriptManager Class

We normally add JavaScript functions to our webpage using <Script> tag. There are situations where we need to add the scripts dynamically from the codebehind class. In .NET Framework 1.x version, there is no class that helps us to handle this situation effectively. This drawback was addressed in .NET Framework 2.0 by introducing a new class called ClientScriptManager.  This class can be used to manage and add script blocks to the asp.net page from codebehind class.

Things we should know about ClientScriptManager Class

·         ClientScript property of the Page object will give us an instance of ClientScriptManager object. We can add the scripts dynamically through this instance which will be then be injected in the HTML output.

·         This class uniquely identifies scripts by a key String and a Type. Scripts with the same key and type are considered duplicates and similar scripts are then avoided. This will avoid the confusion caused when we are adding scripts from user controls. For example, the method IsClientScriptBlockRegistered() can be used for checking duplicate scripts registered for RegisterClientScriptBlock() method.

ClientScriptManager class has a set of useful methods which we can use to inject the JavaScript functions in the HTML output. We can choose to use these methods to accomplish our requirements depending on the situation.

This part of the article will discuss the usages of 3 different methods.

1.    RegisterClientScriptBlock() Method

2.    RegisterStartupScript() Method

3.    RegisterOnSubmitStatement() Method

RegisterClientScriptBlock() Methods

Page.RegisterStartUpScript() and the Page.RegisterClientScriptBlock() methods in .NET Framework 1.x are now considered obsolete. These two methods are now packed with ClientScriptManaget class. The RegisterClientScriptBlock() method allows you to place a JavaScript function at the top of the page and it gets executed on startup of the page (when loading the page in the browser). There is an additional method called IsClientScriptBlockRegistered() in ClientScriptManager which will return true if a script block is already registered with the same key, hence, we can prevent the duplicate script registration.

There are 2 overloads for this method.

Listing 1 - RegisterClientScriptBlock Overloads

ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key, String script) ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key, String script, Boolean addScriptTags)

Usage

Placing this code on page load or a button click makes the script to fire on the start up of subsequent postback.

Listing 2 - 1st overload

ClientScriptManager script = Page.ClientScript;if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert")){script.RegisterClientScriptBlock(this.GetType(), "Alert""<script type=text/javascript>alert('hi')</script>");}

Listing 3 - 2nd overload

ClientScriptManager script = Page.ClientScript;if (!script.IsClientScriptBlockRegistered(this.GetType(), "Alert")){script.RegisterClientScriptBlock(this.GetType(), "Alert""alert('hi')",true);}

Figure 1 - RegisterClientScriptBlock Output

As I said earlier, these methods will make the script block to execute on the startup, thus we can see the alert box before the controls are actually rendered.

RegisterStartupScript() Methods

In this section, we will see the usage ClientScriptManager.RegisterStartupScript() method of ClientScriptManager class. Both, RegisterStartupScript() method and RegisterClientScriptBlock() method will inject Jscript code that will fire during start up of subsequent postback. But the real difference is the former methods will inject the script after the form open tag but before page controls and the RegisterStartupScript() methods will inject the scripts after page controls but before form close tag. This indicates that injecting script using RegisterClientScriptBlock() method, it is not possible to access page controls in the script block. However, using RegisterStartupScript() method we can.

The markups below (Listing 4 and 5) will show a part html output given by the asp.net page when executing these RegisterClientScriptBlock and RegisterStartupScript methods.

Listing 4 - RegisterClientScriptBlock Output

<form name="form1" method="post" action="Default.aspx" id="form1"><div><input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUJMjgzMDgzOTgzZGQfI8LfDKmcT0TXZj8jwrxqI6TOIA==" /></div><script type=text/javascript>alert('hi')</script>

In the above HTML snippet, we can see the script embedded before the page controls, but after form open tag.

Listing 5 - RegisterStartupScript Output

<script type="text/javascript"><!--alert(document.getElementById('txtName').value)// --></script></form></body>

In the above html snippet (Listing 5), we can see the script embedded after the page controls, but before form close tag, thus making the script able to access the page controls as I said earlier.

Overloads

There are 2 overloads for this method.

Listing 6 - RegisterClientScriptBlock Overloads

ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key, String script) ClientScriptManager.RegisterClientScriptBlock (Type typeofscript, String key, String script, Boolean addScriptTags)

Usage

Placing this code on page load or a button click makes the script fire on the start up of subsequent postback. This method also has a method called IsStartupScriptRegistered(), like RegisterClientScriptBlock() methods, which will check for script duplications. Refer to the code below for the implementation of the RegisterClientScriptBlock() method.

Listing 7 - 1st overload

ClientScriptManager script = Page.ClientScript;txtName.Text = "Welcome to AspAlliance!!!";if (!script.IsStartupScriptRegistered (this.GetType(), "Alert")){script.RegisterStartupScript (this.GetType(), "Alert""<script type=text/javascript>alert(document.getElementById('txtName').value)</script>");}

Listing 8 - 2nd overload

ClientScriptManager script = Page.ClientScript;txtName.Text = "Welcome to AspAlliance!!!";if (!script.IsStartupScriptRegistered (this.GetType(), "Alert")){script.RegisterStartupScript (this.GetType(), "Alert""alert(document.getElementById('txtName').value)",true);}

When the above code is executed we will get an output similar to "Figure 2 - RegisterStartupScript Output."

Figure 2 - RegisterStartupScript Output

Here, the script block will get executed after the controls in the page are rendered and the controls in the page will be visible to the script as opposed to RegisterClientScriptBlock() method, refer to the above figure. Thus, we can access the page controls from the script block when using RegisterStartupScript() method.

RegisterOnSubmitStatement() Method

This section will discuss the implementation of ClientScriptManager.RegisterOnSubmitStatement() of ClientScriptManager class. Sometimes, we will require getting confirmation from the user before submitting the form to server. For example, in an input form we would like to get the confirmation from the users before storing it to the database whose validity cannot be determined through validation functions. This method can be used in such situations to provide confirmation dialogs. This method registers scripts which will be executed at the time of submit click of a page.

Listing 9 - Syntax

public void RegisterOnSubmitStatement (    Type type,    string key,    string script)

Usage

Placing this code on page load makes the script fire on every submit click of the webform.

Listing 10 - RegisterOnSubmitStatement

if (!script.IsClientScriptBlockRegistered(this.GetType(), "SubmitScript")){script.RegisterOnSubmitStatement(this.GetType(), "SubmitScript""alert('Submit Clicked')");} 

Consider the code below.

Listing 10 - RegisterOnSubmitStatement Example

protected void Page_Load(object sender, EventArgs e){       ClientScriptManager script = Page.ClientScript;   if (!script.IsClientScriptBlockRegistered(this.GetType(), "SubmitScript")){  script.RegisterOnSubmitStatement(this.GetType(), "SubmitScript""return  confirm('Are you sure to continue')");}}protected void btnSubmit_Click(object sender, EventArgs e){  Response.Write("Form is Submitted.");}

Executing the above code will bring a webform. Clicking Submit will bring a confirm box like the following figure.

Figure 3 - RegisterOnSubmitStatement Output 1

Clicking Cancel will not execute the submit click event, where clicking OK will execute the event and the output will be like Figure 4.

Figure 4 - RegisterOnSubmitStatement Output 2

Conclusion

Thus, we have understood a subset of very useful feature given by the .NET Framework 2.0 in this article. These methods will give the flexibility to handle some of the JavaScript blocks and to very easily add programmatically in the HTML output based on some business requirements. Download the source code attached with this article in the download section to see it in action. Part 2 will discuss the other methods of ClientScriptManager class with some additional JavaScript tips.


RegisterClientScriptInclude() Methods

Most of the time, we wont write our JavaScript code in the ASPX page itself, instead we will put it in a separate file and include the script file by the following include tag in HTML,

Listing 1 - Script Tag

<script src="_scripts/JavaScript.js" type="text/javascript"></script>

 

By using RegisterClientScriptInclude() method of ClientScriptManager class, we can include JavaScript file in the output HTML from the codebehind. This method registers scripts that are in a separate JavaScript file with the Page object.

 

There are 2 overloads for this method,

Listing 2 - RegisterClientScriptInclude overloads

ClientScriptManager.RegisterClientScriptInclude (String key, String Url)

ClientScriptManager.RegisterClientScriptInclude (Type type, String key, String Url)

 

key

A client script include is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates.

 

Url is the actual url of the JavaScript file and type is to register the script with the page object using a type.

 

Usage

Include a JavaScript file in the solution, say inside a folder called “_script” with a simple function,

Listing 3 - JavaScript file

// JavaScript File

function fnJavaScriptTest()

{

alert('Button Clicked');

}

 

Registering the above script file with the object can be done by,

 

Listing 4 - 1st Overload of RegisterClientScriptInclude

    protected void Page_Load(object sender, EventArgs e)

    {      

ClientScriptManager script = Page.ClientScript;

if (!script.IsClientScriptIncludeRegistered("ScriptInFile"))

        {

            script.RegisterClientScriptInclude("ScriptInFile", "_scripts/JavaScript.js");

        }   

 }

 

Listing 5 - 2nd Overload of RegisterClientScriptInclude

    protected void Page_Load(object sender, EventArgs e)

    { 

ClientScriptManager script = Page.ClientScript;

 

  if (!script.IsClientScriptIncludeRegistered(this.GetType(), "ScriptInFile"))

        {

            script.RegisterClientScriptInclude(this.GetType(), "ScriptInFile", "_scripts/JavaScript.js");

        }

 }

 

To call the above script for a submit button click,

Listing 6 -Test RegisterClientScriptInclude

 

if (!script.IsOnSubmitStatementRegistered(this.GetType(), "SubmitScript"))

        {

            script.RegisterOnSubmitStatement(this.GetType(), "SubmitScript", "fnJavaScriptTest()");

        }

 

Executing the above code will inject a script include tag at the top of the page like,

 

Listing 7- RegisterClientScriptInclude Output

<form name="form1" method="post" action="Default.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">

<div>

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTkwNjc4NTIwMWRktsfigKuADpFosbj3fdzgZsEESdc=" />

</div>

<script src="_scripts/JavaScript.js" type="text/javascript"></script>

 

Execute the page and you can see the alert when the page is submitted.

Thus, we have understood how to include a JavaScript file from codebehind and accessing it from client side. Next section we will see about RegisterForEventValidation() method of ClientScriptManager class.

 

RegisterForEventValidation() Methods

This method is introduced in ASP.Net 2.0 for security purposes. Usage of this method will prevent the need for disabling a security check called event validation.

 

What’s New in ASP.Net 2.0?

ASP.Net 2.0 performs a new validation on every postback called EventValidation which records the values, controls at every render and it will check the data and control that is generating the event or postback is in the list recorded in the last render. For example, if a dropdown with values 1, 2, 3 is rendered to the client, for the next postback event if someone tries to add a fourth option say “4” in the client (using JavaScript) and post it to the server the validation fails and the runtime will throw an exception. ASP.Net will predict it as an attack by default since the content are different and will throw an exception.

 

There are 3 overloads,

Listing 8- RegisterForEventValidation Overloads

ClientScriptManager.RegisterForEventValidation (String uniqueid, String value)

ClientScriptManager.RegisterForEventValidation (String uniqueid)

ClientScriptManager.RegisterForEventValidation (PostBackOptions options)

 

uniqueid

The uniqueid of the server control that is generating a server side event or postback.

 

Usage

Sometimes, we need to populate some of the server control like dropdown, ListBox from client side JavaScript. For example, consider a dropdown named ddlLanguages contain some 3 list items which are populated from javascript like,

Listing 9- Add new Options to DropDownList

var oOption = document.createElement("OPTION");

document.all("ddlLanguages").options.add(oOption);

oOption.innerText = "English";           

oOption = document.createElement("OPTION");           

document.all("ddlLanguages").options.add(oOption);

oOption.innerText = "Tamil";

oOption = document.createElement("OPTION");               

document.all("ddlLanguages").options.add(oOption);

oOption.innerText = "Hindi";

 

After this if we try to post this form to the server through a button click, ASP.Net will throw the below error,

 

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

 

Clearly the above message gives a resolution to prevent it i.e. by,

<pages enableEventValidation="false"/> in Web.Config or,

<%@ Page EnableEventValidation="false" %> in a page attribute

 

By doing this, we are giving a way to hacker to intrude by disabling the event validation. This can be prevented by use of RegisterForEventValidation methods of ClientScriptManager class in ASP.Net 2.0. We need to register the server control ID with the all the possible values that can be posted by JavaScript by that control in Render Event of the page. So to prevent the exception in our example,

 

Listing 10- EventValidation Error Resolution

protected override void Render(System.Web.UI.HtmlTextWriter writer)

    {

        ClientScript.RegisterForEventValidation("ddlLanguages ", "English");

        ClientScript.RegisterForEventValidation("ddlLanguages ", "Tamil");

        ClientScript.RegisterForEventValidation("ddlLanguages ", "Hindi");

        base.Render(writer);

    }

 

The 2nd overload can be used to register a server control that is causing the postback event is safe while the 3rd overload deals with the PostBackOptions which specifies how a server control can generate a javascript to do a postback. Refer the msdn link in reference section to read more.

Sponsors

Useful Books For Developers
被过滤广告 More books..

Similar Articles

RegisterExpandoAttribute() Method

Sometimes, we require sending some data to client side for JavaScript calculations which is not required to display. One way of sending this data to the client side is by attaching a custom property to an asp.net control from the server. For example, we can attach a custom attribute to an asp.net button control that holds the server time when the button was last clicked. There can be many other scenarios where we require sending some data to clientside.

This method can be used to register a custom attribute to a control that can be accessed in client side.

 

This method has 2 overloads.

1.      RegisterExpandoAttribute(String controlID, String attribute, String value)  

Registers a name/value pair to a control (controlID), attribute name(attribute), and attribute value(value).

2.      RegisterExpandoAttribute(String, String, String, Boolean)

Registers a name/value pair to a control (controlID), attribute name(attribute), and attribute value(value) and a Boolean value indicating whether to encode the attribute value.

 

 To attach custom property called “LastPostBackTime” to a button control we can use,

 

Listing 11- RegisterExpandoAttribute

Page.ClientScript.RegisterExpandoAttribute(btnSave.ClientID, "LastPostbackTime", DateTime.Now.ToString());

 

To Access the attribute in JavaScript,

Listing 12- Test RegisterExpandoAttribute

  alert(document.getElementById("btnSave").LastPostbackTime);

 

This requirement in 1.x days can be done by,

Listing 13- ExpandoAttribute with 1.x Framework

btnSave.Attributes.Add("LastPostbackTime", DateTime.Now.ToString());

 

The above code will render the control with the attribute name attached to the actual html control and making it not an XHTML complaint. Refer the below output of the above code(Listing 13),

Listing 14- ExpandoAttribute Output in 1.x days

<input type="submit" name="btnSave" value="Save" id="btnSave" LastPostbackTime="19/03/2009 8:41:36 PM" />

 

When we use RegisterExpandoAttribute method to do this, the custom attribute will be segregated in a separate javascript making the control clean. Refer the below output,

Listing 15- RegisterExpandoAttribute Output Element

<script type="text/javascript">

<!--

var btnSave = document.all ? document.all["btnSave"] : document.getElementById("btnSave");

btnSave.LastPostbackTime = "19/03/2009 8:47:24 PM";

// -->

</script>

 

RegisterClientScriptResource() method

This method is used to register a compiled version of resource files in assemblies through WebResource.axd http handler. This method can be mostly used when building custom controls with embedded resources.

 

Listing 16- RegisterClientScriptResource Syntax

public void RegisterClientScriptResource (

    Type type,

    string resourceName

)

 

Moving forward, we will see how to create a simple compiled resource assembly and use it in our website.

 

How to generate a compiled resource assembly?

Consider, we need to make some of JavaScript files as a compiled assembly. To do this, include a new Class Library project to your solution. Add reference to System.Web and System.Security namespace to the class library project. EmbedResource is the project name in our example.

 

Include the JavaScript files under a separate folder in the project. For simplicity purpose, we will include a simple JavaScript method,

 

Listing 16- RegisterClientScriptResource JavaScript File

// JavaScript File

function fnJavaScriptTest()

{

alert('button Clicked');

}

 

The solution will look like the below figure(Figure 1),

Figure 1 - RegisterClientScriptResource Solution

 

Next, include the WebResource Meta data attribute to the namespace for the resources. The WebResource(JavaScript file in our case) should be specified with namespace. Since our JavaScript file is under the folder “Script”, the resource should be specifed as “EmbedResource. Script.JavaScripts.js” in meta attribute as a namespace name. Refer the below code,

 

Listing 17- RegisterClientScriptResource Resource Implementation

using System;

using System.Web;

using System.Web.UI;

using System.Security.Permissions;

 

[assembly: WebResource("EmbedResource.Script.JavaScripts.js", "application/x-javascript")]

namespace EmbedResource

{  

    public class JavaScriptResources

    {

    }

}

 

Now, right click the JavaScript file and click properties. Set the BuildAction property to EmbedResource. Compile the project.

 

How to use this in our Website?

From the website project, add a reference to our resource project. To use the embedded resource, we need to register the resource with the Page object. To do this,

Listing 18 - Using Compiled Resource

Page.ClientScript.RegisterClientScriptResource(typeof(EmbedResource.JavaScriptResources), "EmbedResource.Script.JavaScripts.js");

 

The resource name should be same as the one we have given the class library project.

When we execute our project, we can see the embed resource in our output html similar to below,

Listing 19 - Resource Output

<script src="/JavaScriptEnhancements/WebResource.axd?d=oB4CkRkIqe0GFz8pCjRvZ-vuPnbGGZuo5seCUAwXwgaBMrK9KEdLlMNrYTfCp0Hu0&amp;t=633731779447968750" type="text/javascript"></script>

 

 To test this, include a button and call the javascript function from its onclick event. You will get the alert when the button is clicked.

 

Other Useful Methods

There are another 2 useful methods that are packed with ClientScriptManager class, RegisterArrayDeclaration() and RegisterHiddenField(). As the name suggests, the first method can be used to register an array from codebehind that can be accessed in the client side while the former method is used to register a hidden field.

Visit the link "Javascript Tips for ASP.Net" in Reference section of this article to read some of the useful javascript tips for asp.net applications.


 

RegisterClientScriptInclude() Methods

Most of the time, we wont write our JavaScript code in the ASPX page itself, instead we will put it in a separate file and include the script file by the following include tag in HTML,

Listing 1 - Script Tag

<script src="_scripts/JavaScript.js" type="text/javascript"></script>

 

By using RegisterClientScriptInclude() method of ClientScriptManager class, we can include JavaScript file in the output HTML from the codebehind. This method registers scripts that are in a separate JavaScript file with the Page object.

 

There are 2 overloads for this method,

Listing 2 - RegisterClientScriptInclude overloads

ClientScriptManager.RegisterClientScriptInclude (String key, String Url)

ClientScriptManager.RegisterClientScriptInclude (Type type, String key, String Url)

 

key

A client script include is uniquely identified by its key and its type. Scripts with the same key and type are considered duplicates.

 

Url is the actual url of the JavaScript file and type is to register the script with the page object using a type.

 

Usage

Include a JavaScript file in the solution, say inside a folder called “_script” with a simple function,

Listing 3 - JavaScript file

// JavaScript File

function fnJavaScriptTest()

{

alert('Button Clicked');

}

 

Registering the above script file with the object can be done by,

 

Listing 4 - 1st Overload of RegisterClientScriptInclude

    protected void Page_Load(object sender, EventArgs e)

    {      

ClientScriptManager script = Page.ClientScript;

if (!script.IsClientScriptIncludeRegistered("ScriptInFile"))

        {

            script.RegisterClientScriptInclude("ScriptInFile", "_scripts/JavaScript.js");

        }   

 }

 

Listing 5 - 2nd Overload of RegisterClientScriptInclude

    protected void Page_Load(object sender, EventArgs e)

    { 

ClientScriptManager script = Page.ClientScript;

 

  if (!script.IsClientScriptIncludeRegistered(this.GetType(), "ScriptInFile"))

        {

            script.RegisterClientScriptInclude(this.GetType(), "ScriptInFile", "_scripts/JavaScript.js");

        }

 }

 

To call the above script for a submit button click,

Listing 6 -Test RegisterClientScriptInclude

 

if (!script.IsOnSubmitStatementRegistered(this.GetType(), "SubmitScript"))

        {

            script.RegisterOnSubmitStatement(this.GetType(), "SubmitScript", "fnJavaScriptTest()");

        }

 

Executing the above code will inject a script include tag at the top of the page like,

 

Listing 7- RegisterClientScriptInclude Output

<form name="form1" method="post" action="Default.aspx" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">

<div>

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTkwNjc4NTIwMWRktsfigKuADpFosbj3fdzgZsEESdc=" />

</div>

<script src="_scripts/JavaScript.js" type="text/javascript"></script>

 

Execute the page and you can see the alert when the page is submitted.

Thus, we have understood how to include a JavaScript file from codebehind and accessing it from client side. Next section we will see about RegisterForEventValidation() method of ClientScriptManager class.

 

RegisterForEventValidation() Methods

This method is introduced in ASP.Net 2.0 for security purposes. Usage of this method will prevent the need for disabling a security check called event validation.

 

What’s New in ASP.Net 2.0?

ASP.Net 2.0 performs a new validation on every postback called EventValidation which records the values, controls at every render and it will check the data and control that is generating the event or postback is in the list recorded in the last render. For example, if a dropdown with values 1, 2, 3 is rendered to the client, for the next postback event if someone tries to add a fourth option say “4” in the client (using JavaScript) and post it to the server the validation fails and the runtime will throw an exception. ASP.Net will predict it as an attack by default since the content are different and will throw an exception.

 

There are 3 overloads,

Listing 8- RegisterForEventValidation Overloads

ClientScriptManager.RegisterForEventValidation (String uniqueid, String value)

ClientScriptManager.RegisterForEventValidation (String uniqueid)

ClientScriptManager.RegisterForEventValidation (PostBackOptions options)

 

uniqueid

The uniqueid of the server control that is generating a server side event or postback.

 

Usage

Sometimes, we need to populate some of the server control like dropdown, ListBox from client side JavaScript. For example, consider a dropdown named ddlLanguages contain some 3 list items which are populated from javascript like,

Listing 9- Add new Options to DropDownList

var oOption = document.createElement("OPTION");

document.all("ddlLanguages").options.add(oOption);

oOption.innerText = "English";           

oOption = document.createElement("OPTION");           

document.all("ddlLanguages").options.add(oOption);

oOption.innerText = "Tamil";

oOption = document.createElement("OPTION");               

document.all("ddlLanguages").options.add(oOption);

oOption.innerText = "Hindi";

 

After this if we try to post this form to the server through a button click, ASP.Net will throw the below error,

 

Invalid postback or callback argument.  Event validation is enabled using <pages enableEventValidation="true"/> in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.

 

Clearly the above message gives a resolution to prevent it i.e. by,

<pages enableEventValidation="false"/> in Web.Config or,

<%@ Page EnableEventValidation="false" %> in a page attribute

 

By doing this, we are giving a way to hacker to intrude by disabling the event validation. This can be prevented by use of RegisterForEventValidation methods of ClientScriptManager class in ASP.Net 2.0. We need to register the server control ID with the all the possible values that can be posted by JavaScript by that control in Render Event of the page. So to prevent the exception in our example,

 

Listing 10- EventValidation Error Resolution

protected override void Render(System.Web.UI.HtmlTextWriter writer)

    {

        ClientScript.RegisterForEventValidation("ddlLanguages ", "English");

        ClientScript.RegisterForEventValidation("ddlLanguages ", "Tamil");

        ClientScript.RegisterForEventValidation("ddlLanguages ", "Hindi");

        base.Render(writer);

    }

 

The 2nd overload can be used to register a server control that is causing the postback event is safe while the 3rd overload deals with the PostBackOptions which specifies how a server control can generate a javascript to do a postback. Refer the msdn link in reference section to read more.
 

RegisterExpandoAttribute() Method

Sometimes, we require sending some data to client side for JavaScript calculations which is not required to display. One way of sending this data to the client side is by attaching a custom property to an asp.net control from the server. For example, we can attach a custom attribute to an asp.net button control that holds the server time when the button was last clicked. There can be many other scenarios where we require sending some data to clientside.

This method can be used to register a custom attribute to a control that can be accessed in client side.

 

This method has 2 overloads.

1.      RegisterExpandoAttribute(String controlID, String attribute, String value)  

Registers a name/value pair to a control (controlID), attribute name(attribute), and attribute value(value).

2.      RegisterExpandoAttribute(String, String, String, Boolean)

Registers a name/value pair to a control (controlID), attribute name(attribute), and attribute value(value) and a Boolean value indicating whether to encode the attribute value.

 

 To attach custom property called “LastPostBackTime” to a button control we can use,

 

Listing 11- RegisterExpandoAttribute

Page.ClientScript.RegisterExpandoAttribute(btnSave.ClientID, "LastPostbackTime", DateTime.Now.ToString());

 

To Access the attribute in JavaScript,

Listing 12- Test RegisterExpandoAttribute

  alert(document.getElementById("btnSave").LastPostbackTime);

 

This requirement in 1.x days can be done by,

Listing 13- ExpandoAttribute with 1.x Framework

btnSave.Attributes.Add("LastPostbackTime", DateTime.Now.ToString());

 

The above code will render the control with the attribute name attached to the actual html control and making it not an XHTML complaint. Refer the below output of the above code(Listing 13),

Listing 14- ExpandoAttribute Output in 1.x days

<input type="submit" name="btnSave" value="Save" id="btnSave" LastPostbackTime="19/03/2009 8:41:36 PM" />

 

When we use RegisterExpandoAttribute method to do this, the custom attribute will be segregated in a separate javascript making the control clean. Refer the below output,

Listing 15- RegisterExpandoAttribute Output Element

<script type="text/javascript">

<!--

var btnSave = document.all ? document.all["btnSave"] : document.getElementById("btnSave");

btnSave.LastPostbackTime = "19/03/2009 8:47:24 PM";

// -->

</script>

 

RegisterClientScriptResource() method

This method is used to register a compiled version of resource files in assemblies through WebResource.axd http handler. This method can be mostly used when building custom controls with embedded resources.

 

Listing 16- RegisterClientScriptResource Syntax

public void RegisterClientScriptResource (

    Type type,

    string resourceName

)

 

Moving forward, we will see how to create a simple compiled resource assembly and use it in our website.

 

How to generate a compiled resource assembly?

Consider, we need to make some of JavaScript files as a compiled assembly. To do this, include a new Class Library project to your solution. Add reference to System.Web and System.Security namespace to the class library project. EmbedResource is the project name in our example.

 

Include the JavaScript files under a separate folder in the project. For simplicity purpose, we will include a simple JavaScript method,

 

Listing 16- RegisterClientScriptResource JavaScript File

// JavaScript File

function fnJavaScriptTest()

{

alert('button Clicked');

}

 

The solution will look like the below figure(Figure 1),

Figure 1 - RegisterClientScriptResource Solution

 

Next, include the WebResource Meta data attribute to the namespace for the resources. The WebResource(JavaScript file in our case) should be specified with namespace. Since our JavaScript file is under the folder “Script”, the resource should be specifed as “EmbedResource. Script.JavaScripts.js” in meta attribute as a namespace name. Refer the below code,

 

Listing 17- RegisterClientScriptResource Resource Implementation

using System;

using System.Web;

using System.Web.UI;

using System.Security.Permissions;

 

[assembly: WebResource("EmbedResource.Script.JavaScripts.js", "application/x-javascript")]

namespace EmbedResource

{  

    public class JavaScriptResources

    {

    }

}

 

Now, right click the JavaScript file and click properties. Set the BuildAction property to EmbedResource. Compile the project.

 

How to use this in our Website?

From the website project, add a reference to our resource project. To use the embedded resource, we need to register the resource with the Page object. To do this,

Listing 18 - Using Compiled Resource

Page.ClientScript.RegisterClientScriptResource(typeof(EmbedResource.JavaScriptResources), "EmbedResource.Script.JavaScripts.js");

 

The resource name should be same as the one we have given the class library project.

When we execute our project, we can see the embed resource in our output html similar to below,

Listing 19 - Resource Output

<script src="/JavaScriptEnhancements/WebResource.axd?d=oB4CkRkIqe0GFz8pCjRvZ-vuPnbGGZuo5seCUAwXwgaBMrK9KEdLlMNrYTfCp0Hu0&amp;t=633731779447968750" type="text/javascript"></script>

 

 To test this, include a button and call the javascript function from its onclick event. You will get the alert when the button is clicked.

 

Other Useful Methods

There are another 2 useful methods that are packed with ClientScriptManager class, RegisterArrayDeclaration() and RegisterHiddenField(). As the name suggests, the first method can be used to register an array from codebehind that can be accessed in the client side while the former method is used to register a hidden field.

Visit the link "Javascript Tips for ASP.Net" in Reference section of this article to read some of the useful javascript tips for asp.net applications.

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

日历

Search

  •  

最新评论及回复

最近发表

Powered By Z-Blog 1.8 Spirit Build 80722 Code detection by Codefense

Copyright 2008-2011 京公网安备 110115000655 京ICP备09005635号 www.qtasp.cn WebSite. All Rights Reserved.