Friday, November 15, 2013

Access Server-Side Variables, Property In External JavaScript: C#

Accessing Server-Side Variables, Property In External  JavaScript: C#

At times there may be a requirement to access the server-side variables in External JavaScript. To achieve the same we can follow the following:

The language used for server-side variable is c#.

For a server-side variable to be accessed in External JavaScript, the variable declared must be public.

Server-Side C# Code:

 public string strTempVar = "some value";  

JavaScript Code:

 <script type="text/javascript" language="javascript">  
   var strTempVarValue = "<%= strTempVar%>";  
 <%-- Add the external script reference where server side variable value needs to be accessed--%>  
 <script src="path of the externalJavaScript.js" type="text/javascript"></script>  

This is how we can access a server-side variable in external JavaScript File. The variable strTempVarValue would now be accessible in external JavaScript.

The same can be used for accessing property as well.

Vivek Joshi

No comments: