65.9K
CodeProject is changing. Read more.
Home

Accessing C# Variables in JavaScript

starIconstarIconstarIconstarIconstarIcon

5.00/5 (7 votes)

Jul 14, 2012

CPOL
viewsIcon

132457

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

Introduction

So often I come across this question on various forums - '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 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 on the client side (JavaScript in aspx page) and can be accessed like:

<script>
    function GetMyName()
    {
	alert(myName);
    }
</script>