【问题标题】:Passing value from code-behind to Javascript将值从代码隐藏传递到 Javascript
【发布时间】:2011-04-13 22:15:08
【问题描述】:

我正在使用 jQueryUI ProgressBar 向用户显示他们使用了多少允许的文件存储空间。该百分比在代码隐藏中计算,应传递给 Javascript。

Aspx 代码

    <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
        <script type="text/javascript">
            $(function () {
                var pct = document.getElementById("filesPercentage").value;
                $("#progressbar").progressbar({
                    value: pct
                });
            });
        </script>
    </asp:Content>

    <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
      ...
     <input type="hidden" runat="server" id="filesPercentage" />                      
     <div id="progressbar"></div>         
      ...
    </asp:Content>

代码背后

protected void Page_Load(object sender, EventArgs e)
{
   filesPercentage.Value = "85";
}

似乎无法从隐藏字段中获取百分比数字。任何帮助将不胜感激。

【问题讨论】:

  • 查看源码隐藏字段是否包含值?
  • filesPercentage 在呈现后可能不会成为控件的 id。

标签: c# javascript jquery asp.net ajax


【解决方案1】:

您需要获取隐藏输入的渲染 id

var pct = document.getElementById("<%=filesPercentage.ClientID%>").value;

从您在服务器上运行输入的那一刻起,最好使用asp:HiddenField 而不是input

【讨论】:

    【解决方案2】:

    由于您的隐藏字段是服务器控件,因此 ID 可能会生成为 filesPercentage 以外的其他内容(可能类似于 ctl00_ctl00_filesPercentage

    • 您可能需要将生成的客户端 ID 应用到您的 javascript document.getElementById("&lt;%=filesPercentage.ClientID%&gt;").value;
    • 或者使用其他方式选择隐藏值,比如$('[hidden's parent element] input[type="hidden"]').val()

    此外,进度条值似乎需要一个数字,因此您可能需要执行 value: pct * 1value: parseInt(pct)

    http://jsfiddle.net/pxfunc/QyZSs/

    【讨论】:

    • 很好地解决了我的第一个问题并预测了我会遇到的下一个问题。这非常有效。
    【解决方案3】:

    试试这个

    var pct = document.getElementById("<%=filesPercentage.ClientID %>").value;
    

    【讨论】:

      【解决方案4】:

      .net 将修改您为控件提供的 id 以确保它是唯一的,因此您不会使用正确的 id 访问它。如果您给隐藏字段一个唯一的类名,您可以通过这种方式访问​​该值:

      <input type="hidden" runat="server" id="filesPercentage" class="hiddenClass" /> 
      var pct = $('.hiddenClass').val();
      

      【讨论】:

        【解决方案5】:

        恕我直言,这有点干净:-)

        $("#progressbar").progressbar({
          value: $("#<%=filesPercentage.ClientID%>").val()
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-03-30
          • 2010-10-21
          • 2014-01-01
          • 1970-01-01
          相关资源
          最近更新 更多