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.
|