How do I give JavaScript variables data from ASP.NET variables? How do I give JavaScript variables data from ASP.NET variables? asp.net asp.net

How do I give JavaScript variables data from ASP.NET variables?


Probably best easiest to expose them as properties of your page (or master page if used on every page) and reference them via page directives.

 <script type="text/javascript">     var userID = '<%= UserID %>';     var courseID = '<%= CourseID %>';     .... more stuff.... </script>

Then set the values on Page_Load (or in the Page_Load for the master page).

  public void Page_Load( object source, EventArgs e )  {        UserID = Session["userID"];        CourseID = Session["courseID"];        ...  }


@tvanfosson's answer is how I have normally done this in the past, but was just trying to think of something a bit more elegant. Thought I'd throw this out there.

You can set up a HashTable in the codebehind and also initialize a JavaScriptSerializer:

Protected json As New System.Web.Script.Serialization.JavaScriptSerializerProtected jsvars As New Hashtable

Then set variables like this:

jsvars.Add("name", "value")

Then serialize the variables into JavaScript in your page:

<script type="text/javascript">    var vars = <%=json.Serialize(jsvars)%>;    alert(vars.name);</script>

This ensures that all variables are properly escaped and also minimizes the code if you need to work with a lot of variables.


All the answers here that suggest something like

var userID = '<%= UserID %>';

are all missing something important if the variable you are embedded can contain arbitrary string data. The embedded string data needs to be escaped so that if it contains backslashes, quotes or unprintable characters they don't cause your Javascript to error.

Rick Strahl has some suggestions for the escaping code needed here.Using Rick's code the embedded variable will look like this:

var userId = <%= EncodeJsString(UserID) %>;

Note that there are no quotes now, Rick's code wraps the escaped string with quotes.