How to access the variables/properties from C# in JavaScript?

The one shortcut we used to use during the (good old) ASP days, and which still works in ASP.NET is to declare apublic 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%>

To do it nicely, you can use RegisterClientScriptBlockRegisterClientScriptBlock 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>
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s