Introduction
So often I come across this question on various forums that ‘How to access the variables/properties from C# in Javascript?’. And this is one of the scenarios which you are (most) likely to come across if you are writing an ASP.Net application.
For most beginners, it might get confusing as they start wondering how to pass on information from a server side variable to client side.
Solution
The one shortcut we used to used during the (good old) ASP days, and which still works in ASP.NET is to declare a public property in codebehind. Let us say we declare a string variable firstName in codebehind.
public string firstName = "Manas";
public string lastName = "Bhardwaj";
Now, we can access this in aspx page/javascript like this:
<script>
var myName;
function GetMyName()
{
myName = <%=this.firstName%> + ' ' + <%=this.lastName%>;
alert(myName);
}
</script>
To do it nicely, you can useĀ RegisterClientScriptBlock. RegisterClientScriptBlock accepts the following parameters:
Type: The type of the client script to register.
key: The key of the client script to register.
script: The client script literal to register.
addScriptTags: A Boolean value indicating whether to add script tags.
string script = string.Format("var myName = '{0} {1}';", firstName, lastName);
if (!ClientScript.IsClientScriptBlockRegistered("myScript"))
{
ClientScript.RegisterClientScriptBlock(typeof(_Default), "myScript", script, true);
}
Once done, the variable ‘myName’ is available at the client side (javascript in aspx page) and can be accessed like:
<script>
function GetMyName()
{
alert(myName);
}
</script>
Be First to Comment