简体   繁体   English

从我的.aspx页面获取javascript变量的值

[英]get the values of javascript variables from my .aspx page

SO my task is simple - I've I have a javascript code (actually a code that works with google analytics; anaway that's not important) 所以我的任务很简单-我有一个javascript代码(实际上是可与Google Analytics(分析)一起使用的代码;那并不重要)

<script>

     ga('ecommerce:addTransaction', {
                'id': '52',                 

                'revenue': '599.200',               

            });
          </script>

the problem is that these values of id and 'revenue ' I should get it from the server - in this case my aspx page. 问题是id和'revenue'的这些值我应该从服务器获取-在这种情况下是我的aspx页面。

so in my aspx.cs I've got one so simple method which returns an object which has id and revenue property; 所以在我的aspx.cs中,有一个非常简单的方法,该方法返回一个具有id和Revenue属性的对象; SO the task is I shoudld somehow connect my javascript variables with these properties 所以任务是我应该以某种方式将我的javascript变量连接

 protected OrderIndo RenderScript()
  {
    //if (this.OrderID == null) return;

    OrderIndo orderInfo = new OrderInfo();
    orderInfo.id = 12;
    orderInfo.revenue = somestringvariable; 

    return orderInfo;


  }

Create a protected variable of OrderIndo at the beginning of your class in codebehind. 在类OrderIndo的代码开头,创建OrderIndoprotected变量。 Fill it in on PageLoad. 将其填写在PageLoad上。 Render it on your aspx page using 使用以下命令将其呈现在aspx页面上

<script>

     ga('ecommerce:addTransaction', {
                'id': '<%=OrderIndo.id%>',                 

                'revenue': '<%=OrderIndo.revenue%>',               

            });
 </script>

As you used the asp.net tag, I assumed you're using Asp.Net Web Forms. 当您使用asp.net标记时,我假设您正在使用Asp.Net Web窗体。

You can simply register the javascript in your code behind, like this: 您可以在后面的代码中简单地注册javascript,如下所示:

    string gaScript = "<script>ga('ecommerce:addTransaction', { 'id': '{0}', 'revenue': '{1}',  });</script>";
    Page.ClientScript.RegisterStartupScript(GetType(), "ga", string.Format(gaScript, orderInfo.id, orderInfo.revenue));

Or register the variables in code behind: 或者在后面的代码中注册变量:

string gaScript = "<script>var gaId='{0}'; var gaRevenue='{1}'</script>";
            Page.ClientScript.RegisterStartupScript(GetType(), "ga", string.Format(gaScript, orderInfo.id, orderInfo.revenue));

And read the variables in javascript: 并阅读javascript中的变量:

<script>

     ga('ecommerce:addTransaction', {
                'id': gaId,                 

                'revenue': gaRevenue,               

            });
          </script>

Hope it helps 希望能帮助到你

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM