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

9

27

I have created a SCORM API for our LMS and right now I am using hard coded userID and courseID variables (variables that reference things in the database). I need to pass the real userID and courseID instead of using hard coded ones. I know the userID is stored in the session and the courseID is passed over from the launch page.

How do I get these into JavaScript so I can include them in my calls to the .ashx that handles the SCORM calls?

Navigable answered 16/2, 2009 at 16:7 Comment(0)
E
45

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"];
        ...
  }
Emotional answered 16/2, 2009 at 16:13 Comment(5)
Don't forget that the embedded Javascript string needs to be escaped, otherwise back slashes, quotes and the like in the string will break you Javascript on the client side.Microelectronics
@Microelectronics -- noted, but it's reasonably likely that an id field is going to be a numeric value and not be a problem.Emotional
Many of the user ids in systems that I deal with are strings which are entered by the sysadmin. Which is why the name o'brien makes a very good test case. It is usually best to be defensive and not assume that variables you are embedding are not Javascript string safe.Microelectronics
var SelectArray = [<%= CropSelectArray %>] ; for arraysBruno
This may not be relevant as this answer is 7 years old, but isn't including script tags inside .aspx pages frowned upon for performance reasons?Vining
M
9

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.

Microelectronics answered 16/2, 2009 at 18:6 Comment(2)
Some people may want to have that work be done by the client rather than on the server. Either way, it is important to point out that once you get the data where you want it, it needs to be cleaned up, parsed, inspected, and not just instantly consumed.Grof
Huh ? How it is possible to this this work on the client ? The text needs to be escaped before it can be embedded in the javascript variable.Microelectronics
R
9

@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.JavaScriptSerializer
Protected 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.

Receivership answered 2/1, 2012 at 19:23 Comment(0)
C
6

This article describes the most pragmatic solution several pragmatic solutions to your problem.

Crosshatch answered 16/2, 2009 at 16:11 Comment(4)
Not clear to me why that solution is the most "pragmatic." Seems way too complex based on what he needs.Joceline
Good point - I edited my answer to better reflect the article's contentsCrosshatch
None of them appear to deal with the escaping issues of embedding a Javascript string with arbitrary string data.Microelectronics
Whilst this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference.Racemic
F
4

Here are the steps that you will have to take:

In your code behind page:

private int _userId;
private int _courseId;
protected int CourseId
{
  get { return _courseId;}
  set { _courseId = value;}
}
protected int UserId
{
 get { return _userId;}

set { _userId = value;}
}

Step 2 : based on your requirement now you have to set up those properties. The catch is that these properties should be set before they are referenced from the JavaScript. Maybe something like this in the Page_Load event:

_userId = Session["userId"];
_courseId = Request.QueryString["CourseId"] != null ? Request.QueryString["CourseId"] : String.empty;

Of course you can parse them to appropriate types based on your requirements.

Finally, you can reference them in JavaScript as follows:

var currentUserId = '<% = UserId %>';
var currentCouseId = '<% = CourseId %>';

This should definitely work. I have used this approach many times.

Flagrant answered 16/2, 2009 at 18:55 Comment(0)
S
2

In Passing .NET Server-Side Data to JavaScript, I list various approaches, including:

  1. Fetching Data by Making an AJAX Request
  2. Loading Data Through an External JavaScript File
  3. Opening a Persistent Connection with SignalR
  4. Attaching Data to HTML Elements
  5. Assigning Data Directly to a JavaScript Variable
  6. Serializing a .NET Object into a JavaScript Literal
Spearwort answered 16/11, 2014 at 17:59 Comment(0)
G
0

I'm not sure about SCORM or .ashx files (no experience there) but as far as getting values from ASP.NET you can do all sorts of things like

var xyz = '<%= variable %>';

from within your ASP.NET page. There are various ways to accomplish this but the end result is that the ASP.NET page renders the values of the variable in the HTML (or JavaScript) that is sent to the browser.

This is a generic ASP.NET and JavaScript answer, there may be a more elegant solution out there for you.

Grof answered 16/2, 2009 at 16:12 Comment(0)
J
0

You can also use HTTP cookies. That approach is nice if you need to pass values the other direction as well.

Joceline answered 16/2, 2009 at 16:36 Comment(0)
T
0

I am in the process of doing the same thing. I am just passing whatever values I may need upon initialization and such in the API object's constructor. I have not seen any requirements as to how the API object can be created, just how it is located in the SCO's code.

Triserial answered 19/8, 2009 at 17:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.