CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Using JavaScript Effectively in ASP.Net 2.0 – PART 2

By Satheesh Babu
Posted On Mar 22,2009
Article Rating:
Be first to rate
this article.
No of Comments: 1
Category: ASP.Net
Print this article.

Using JavaScript Effectively in ASP.Net 2.0 – PART 2

 

Introduction

In Part 1 of this article, we have seen some of the basic usages of new ClientScriptManager class that assists in client side interactions in asp.net applications. Unfortunately, msdn is not having enough documentation which can help us to understand the features of this class better. Moving forward, part 2 of this article we will see more about the left out methods in ClientScriptManager class and its usages.

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.

 

Reference

PostBackOptions class

JavaScript Tips for ASP.Net

 

Downloads

Download Source

 

Conclusion

Thus, with this article series we have understood some of the most useful and frequently used JavaScript enhancements that are done with ASP.Net 2.0. We will end this article series “Using Javascript Effectively in ASP.Net 2.0” with the current part (part 2). Download the source attached with this article and see it in action.

Happy Coding!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Using JavaScript Effectively in ASP.Net 2.0 – PART 2
Wow, I never knew I was missing so much deep inside the scriptmanager. Thanks