如何从ASP.NET变量中提供JavaScript变量数据?

时间:2021-04-25 03:38:04

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.

我为LMS创建了一个SCORM API,现在我正在使用硬编码的userID和courseID变量(引用数据库中的东西的变量)。我需要传递真实的userID和courseID,而不是使用硬编码的。我知道userID存储在会话中,courseID从启动页面传递。

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

如何将这些内容导入JavaScript中,以便将其包含在我对处理SCORM调用的.ashx的调用中?

9 个解决方案

#1


41  

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).

然后在Page_Load(或主页面的Page_Load)中设置值。

  public void Page_Load( object source, EventArgs e )
  {

        UserID = Session["userID"];
        CourseID = Session["courseID"];
        ...
  }

#2


7  

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.

如果您嵌入的变量可以包含任意字符串数据,则都会遗漏一些重要内容。嵌入的字符串数据需要进行转义,这样如果它包含反斜杠,引号或不可打印的字符,则不会导致Javascript出错。

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

Rick Strahl对此处所需的转义代码有一些建议。使用Rick的代码,嵌入变量将如下所示:

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

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

请注意,现在没有引号,Rick的代码用引号包装转义字符串。

#3


7  

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

@ tvanfosson的答案是我过去通常如何做到这一点,但只是想把事情想象得更优雅一点。以为我会把它扔出去。

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

您可以在代码隐藏中设置HashTable并初始化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:

然后在页面中将变量序列化为JavaScript:

<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.

这样可以确保所有变量都被正确转义,并且如果需要处理大量变量,还可以最小化代码。

#4


4  

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

本文介绍了最实用的解决方案,为您的问题提供了几种实用的解决方案。

#5


3  

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:

第2步:根据您的要求,您必须设置这些属性。问题是这些属性应该在从JavaScript引用之前设置。在Page_Load事件中可能是这样的:

_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:

最后,您可以在JavaScript中引用它们,如下所示:

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

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

这绝对有用。我多次使用过这种方法。

#6


1  

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

在将.NET服务器端数据传递给JavaScript时,我列出了各种方法,包括:

  1. Fetching Data by Making an AJAX Request
  2. 通过发出AJAX请求获取数据
  3. Loading Data Through an External JavaScript File
  4. 通过外部JavaScript文件加载数据
  5. Opening a Persistent Connection with SignalR
  6. 与SignalR打开持久连接
  7. Attaching Data to HTML Elements
  8. 将数据附加到HTML元素
  9. Assigning Data Directly to a JavaScript Variable
  10. 直接将数据分配给JavaScript变量
  11. Serializing a .NET Object into a JavaScript Literal
  12. 将.NET对象序列化为JavaScript文字

#7


0  

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

您也可以使用HTTP cookie。如果你需要将值传递给另一个方向,那么这种方法很好。

#8


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.

我正在做同样的事情。我只是在初始化时传递我可能需要的任何值,例如在API对象的构造函数中。我没有看到有关如何创建API对象的任何要求,以及它在SCO代码中的位置。

#9


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

我不确定SCORM或.ashx文件(没有经验)但是从ASP.NET获取值你可以做各种各样的事情,比如

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.

从您的ASP.NET页面中。有多种方法可以实现此目的,但最终结果是ASP.NET页面呈现发送到浏览器的HTML(或JavaScript)中的变量值。

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

这是一个通用的ASP.NET和JavaScript答案,可能有更优雅的解决方案供您使用。

#1


41  

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).

然后在Page_Load(或主页面的Page_Load)中设置值。

  public void Page_Load( object source, EventArgs e )
  {

        UserID = Session["userID"];
        CourseID = Session["courseID"];
        ...
  }

#2


7  

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.

如果您嵌入的变量可以包含任意字符串数据,则都会遗漏一些重要内容。嵌入的字符串数据需要进行转义,这样如果它包含反斜杠,引号或不可打印的字符,则不会导致Javascript出错。

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

Rick Strahl对此处所需的转义代码有一些建议。使用Rick的代码,嵌入变量将如下所示:

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

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

请注意,现在没有引号,Rick的代码用引号包装转义字符串。

#3


7  

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

@ tvanfosson的答案是我过去通常如何做到这一点,但只是想把事情想象得更优雅一点。以为我会把它扔出去。

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

您可以在代码隐藏中设置HashTable并初始化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:

然后在页面中将变量序列化为JavaScript:

<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.

这样可以确保所有变量都被正确转义,并且如果需要处理大量变量,还可以最小化代码。

#4


4  

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

本文介绍了最实用的解决方案,为您的问题提供了几种实用的解决方案。

#5


3  

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:

第2步:根据您的要求,您必须设置这些属性。问题是这些属性应该在从JavaScript引用之前设置。在Page_Load事件中可能是这样的:

_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:

最后,您可以在JavaScript中引用它们,如下所示:

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

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

这绝对有用。我多次使用过这种方法。

#6


1  

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

在将.NET服务器端数据传递给JavaScript时,我列出了各种方法,包括:

  1. Fetching Data by Making an AJAX Request
  2. 通过发出AJAX请求获取数据
  3. Loading Data Through an External JavaScript File
  4. 通过外部JavaScript文件加载数据
  5. Opening a Persistent Connection with SignalR
  6. 与SignalR打开持久连接
  7. Attaching Data to HTML Elements
  8. 将数据附加到HTML元素
  9. Assigning Data Directly to a JavaScript Variable
  10. 直接将数据分配给JavaScript变量
  11. Serializing a .NET Object into a JavaScript Literal
  12. 将.NET对象序列化为JavaScript文字

#7


0  

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

您也可以使用HTTP cookie。如果你需要将值传递给另一个方向,那么这种方法很好。

#8


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.

我正在做同样的事情。我只是在初始化时传递我可能需要的任何值,例如在API对象的构造函数中。我没有看到有关如何创建API对象的任何要求,以及它在SCO代码中的位置。

#9


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

我不确定SCORM或.ashx文件(没有经验)但是从ASP.NET获取值你可以做各种各样的事情,比如

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.

从您的ASP.NET页面中。有多种方法可以实现此目的,但最终结果是ASP.NET页面呈现发送到浏览器的HTML(或JavaScript)中的变量值。

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

这是一个通用的ASP.NET和JavaScript答案,可能有更优雅的解决方案供您使用。