Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Accessing C# Variables in JavaScript

0.00/5 (No votes)
13 Jul 2012 1  
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%>

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>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here