ASP.net标签在代码中获得价值

时间:2012-11-06 16:21:03

标签: jquery asp.net code-behind

嘿所有我想在我的代码中从标签中获取值:

<div id="chkHaz" data-checked="no">
   <asp:Label ID="lblchkHaz" runat="server" Text="no" ClientIDMode="Static" Style="visibility: hidden; display: none;"></asp:Label>
   <asp:Image ID="check_chkHaz" runat="server" ImageUrl="~/images/chkOFF.png" ClientIDMode="Static" />
</div>

我根据用户是否通过JQuery“检查”它来设置它:

$("#chkHaz").click(function (input) {
   if ($(this).attr("data-checked") == "no") {
      $('#check_' + $(this).attr('id')).attr("src", "/images/chkON.png");
      $(this).attr("data-checked", "yes");
      $('#lbl' + $(this).attr('id')).attr("text", "yes");
      $('#lbl' + $(this).attr('id')).html("yes");
   } else {
      $('#check_' + $(this).attr('id')).attr("src", "/images/chkOFF.png");
      $(this).attr("data-checked", "no");
      $('#lbl' + $(this).attr('id')).attr("text", "no");
      $('#lbl' + $(this).attr('id')).html("no");
   }
});

然而,当我通过后面的代码检查它时:

Dim strChkHaz As String = lblchkHaz.text & ""

总是“不”即使我知道它改变了的“ HTML值”没有“ > “是”“文字”“否”“是”

enter image description here

更改为...

enter image description here

3 个答案:

答案 0 :(得分:2)

标签值未回发您必须使用隐藏字段。您可以使用标签在客户端浏览器上显示值,但要在回发时发送值,您需要使用隐藏字段。

您可以使用input,type =“hidden”或asp:hidden字段来检索label的值。

在html中

<input type="hidden" runat=server ID="hdnForLabel" />

在jquery中

$('<%= hdnForLabel %>').value = "some value";

代码隐藏

string strLabelVal = hdnForLabel.Value;

答案 1 :(得分:1)

1)在.aspx文件中添加

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

2)在JS中找到隐藏字段并在更改标签时同时更新它。

3)现在在代码中,从隐藏字段中读取.Value属性,而不是查看标签文本。

答案 2 :(得分:0)

首先看起来你的选择器是错误的。将runat="server"应用于ASP.NET控件时,id将与容器一起添加。所以你的id看起来与HTML中的id不同。所以在这种情况下你需要使用Attribute starts with或attribute has selector

$('#check_' + $(this).attr('id'))

必须

$('[id*="check_' + $(this).attr('id') + '"]')