【问题标题】:Read text from ASP Label Control (populated by jquery)从 ASP 标签控件中读取文本(由 jquery 填充)
【发布时间】:2019-10-23 05:56:40
【问题描述】:

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
  $(document).ready(function() {
    $("button").click(function() {
      var items = [];
      $.each($("input[name]:checked"), function() {
        items.push($(this).val());
      });
      //alert("You entered: " + items.join(", "));
      if (items.length === 0) {
        $('#<%=Label1.ClientID%>').html("No data to display.");
      } else {
        items = items.join(", ");
        $('#<%=Label1.ClientID%>').html("You selected the following options: " + "<br />");
        $('#<%=txtTestVar1.ClientID%>').html(items);
      }
    });
  });
</script>

<button type="button" runat="server">Update Choices <i class="fas fa-retweet"></i></button>
<br />
<br />
<asp:Label runat="server" ID="Label1"></asp:Label>
<asp:Label runat="server" ID="txtTestVar1"></asp:Label>

protected void btnSave_Click(object sender, EventArgs e) { lblNotification.Text = txtTestVar1.Text.ToString(); }

我使用 Jquery 在 html 页面上填充了一个标签,效果很好。但是,当我尝试从刚刚填充的那个标签中读取(通过使用后面的代码 - c#)时,它返回一个空字符串。谁能解释这是为什么?

【问题讨论】:

    标签: javascript c# jquery css asp.net


    【解决方案1】:

    标签的文本/值不包含在回发负载数据中。

    您必须将数据存储在HiddenField(或TextBox)而不是Label,例如。

    <asp:HiddenField runat="server" ID="txtTestVar1"></asp:HiddenField>
    

    并在客户端通过 jQuery val 而不是 html 设置数据。

    $('#<%=txtTestVar1.ClientID%>').val(items);
    

    在服务器端,您通过隐藏字段Value 属性获取值。

    protected void btnSave_Click(object sender, EventArgs e) 
    {
        var value = this.txtTestVar1.Value;
        // ...
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-08
      • 1970-01-01
      • 2010-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多