How to Pass Values from CodeBehind to JavaScript?
Using HiddenField
Using a HiddenField control is one of
the very common options which we can use to send some values from server to
clientside. You can do this, by declaring a HTML INPUT control with type as
hidden and setting runat attribute to server. Another way is to drag and drop a
HiddenField control from visual studio toolbox.
ASPX
<script
src="scripts/jquery-1.4.1.min.js"
type="text/javascript"></script>
<script
type="text/javascript">
$(document).ready(function()
{
alert($("#hfServerValue").val());
});
</script>
</head>
<body>
<form id="form1"
runat="server">
<div>
<asp:HiddenField ID="hfServerValue"
runat="server" />
Codebehind
protected void Page_Load(object sender,
EventArgs e)
{
hfServerValue.Value = "From
Server";
}
Setting a Javascript Variable using
<% %> blocks
We can embed the C# code using the
<% %> construct in ASPX page. To do this, declare a public variable and
assign it to a javascript variable through <% %> construct. Refer
below,
ASPX
<script
src="scripts/jquery-1.4.1.min.js"
type="text/javascript"></script>
<script
type="text/javascript">
$(document).ready(function()
{
var servervalue =
'<%=FromServer %>';
alert(servervalue);
});
</script>
</head>
<body>
<form id="form1"
runat="server">
Codebehind
public string FromServer;
protected void Page_Load(object
sender, EventArgs e)
{
FromServer = "From
Server";
}
Declaring JavaScript Variable from
CodeBehind
This is one another way where we can
declare a javascript variable by constructing the javascript from codebehind and
assign a value. Refer the below code,
ASPX
<script
src="scripts/jquery-1.4.1.min.js"
type="text/javascript"></script>
<script
type="text/javascript">
$(document).ready(function()
{
alert(JSVar);
});
</script>
CodeBehind
public string FromServer;
protected void Page_Load(object
sender, EventArgs e)
{
FromServer = "From
Server";
StringBuilder strScript = new
StringBuilder();
strScript.Append("<script
type=\"text/javascript\">");
strScript.Append("var
JSVar='");
strScript.Append(FromServer);
strScript.Append("';");
strScript.Append("</script>");
ClientScriptManager script =
Page.ClientScript;
if
(!script.IsClientScriptBlockRegistered(this.GetType(), "Var"))
{
script.RegisterClientScriptBlock(this.GetType(), "Var",
strScript.ToString());
}
}
Once executed, the above code will emit
the javascript variable with a value to the output HTML(similar to below).
<body>
<form name="form1" method="post"
action="CBTOJS.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE"
id="__VIEWSTATE" value="/wEPDwUJNTM4NjU4ODE1ZGQElWxBiEc2w9QhtjJyaVl59BWiPw=="
/>
</div>
<script type="text/javascript">var
JSVar='From Server';</script>
Using Expando Attribute
Another way of sending some information
or data from server to client side is by adding a custom attribute to a control
through AttributeCollection of that control. For example,
btnSave.Attributes.Add("flag", "From
ASP.Net!");
The above custom attribute can be
accessed in javascript like below,
<script
src="scripts/jquery-1.4.1.min.js"
type="text/javascript"></script>
<script
type="text/javascript">
$(document).ready(function() {
alert($('#btnSave').attr("flag"));
});
</script>
The main disadvantage of the above
approach is, the HTML generated by the ASP.Net for the above code is not XHTML
complaint since flag is not a valid attribute of INPUT control. Below is the
HTML generated when we use AttributeCollection.
<input type="submit" name="btnSave"
value="Save" id="btnSave" flag="From ASP.Net!" />
To prevent this, the
ClientScriptManager class has a method called RegisterExpandoAttribute() which
can be used. This method can be used add a custom attribute a control which can
be accessed in clientside by making it XHTML complaint.
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,
Page.ClientScript.RegisterExpandoAttribute(btnSave.ClientID,
"LastPostbackTime", DateTime.Now.ToString());
To Access the attribute in
JavaScript,
alert(document.getElementById("btnSave").LastPostbackTime);
Or you can use the above jquery
script.
When we use RegisterExpandoAttribute
method, the custom attribute will be segregated in a separate javascript making
the control clean and XHTML complaint. Refer the below output,
<script
type="text/javascript">
<!--
var btnSave = document.all ?
document.all["btnSave"] : document.getElementById("btnSave");
btnSave.LastPostbackTime = "19/03/2009
8:47:24 PM";
// -->
</script>
|