【问题标题】:How to maintain the value of label after postback in Asp.net? [closed]在 Asp.net 中回发后如何保持标签的值? [关闭]
【发布时间】:2014-01-03 15:30:59
【问题描述】:

在 asp.net 页面中,我需要知道如何维护通过单击 html 按钮分配的特定标签的值。回发完成后。

详细代码:

 <table>
        <tr>
            <td><asp:Label ID="lbl1" runat="server" ClientIDMode="Static">Before Changing</asp:Label></td>

            <td><asp:Label id="lbl2" runat="server" ClientIDMode="Static"></asp:Label></td>

            <td><asp:TextBox ID="txtbox" runat="server"></asp:TextBox></td>

</tr>

        <tr>
            <td><asp:Button ID="btnasp" runat="server"  Text="ASP Button" Height="50px" Width="150px" OnClick="btnasp_Click"/></td>

            <td><input type="button" id="btnhtml" value="HTML Button" onclick="showlabel()"  style="height:50px; width:150px"/></td>
        </tr>

    </table>

脚本

 <script type="text/javascript">
    function showlabel() {
        $('#lbl1').text("After Changing");

        }
</script>

cs 代码

   protected void btnasp_Click(object sender, EventArgs e)
    {

        txtbox.Text = lbl1.Text;
    }

输出

如果我单击 HTML 按钮,更改前的标签文本将更改为更改后。然后我在更改值后单击 ASP 按钮显示在文本框中。

这是在隐藏字段中添加值且不使用服务器控件到 html 按钮的情况下完成的。这怎么可能?

【问题讨论】:

  • 我真希望我知道你在问什么......
  • @T McKeown 如果我承认你..?
  • @Gurunathan 供将来参考 - 如果您使用句子大小写而不是 title case,问题会更容易阅读。

标签: c# asp.net postback


【解决方案1】:

label 被转换为 span 元素,而 html 元素,如 span 或 div,没有 ViewState。这些文本或 html 均未发送 服务器端像form 元素。

发布的表单元素是输入元素以及hidden 字段。 ASP.net 使用隐藏字段和输入元素维护 ViewState。

恐怕您必须使用隐藏字段来维护回发之间的标签值。

HTML

<input id="hdnLabelState" type="hidden" runat="server" >

Javascript

document.getElementById('<%= hdnLabelState.ClientID %>').value = "changed value of span";

服务器端(代码隐藏)

string changedLabelValue = hdnLabelState.Value;

【讨论】:

  • 感谢您的解决方案。但我不知道如何实现是代码到我的代码中给出上面。我是 .net 的初学者,所以请告诉...
  • 我需要这个没有隐藏字段......
  • 你能解释一下为什么你需要没有隐藏字段吗?
  • 我不能为每个标签控件使用隐藏字段
  • 您可以对所有标签使用单个隐藏字段,例如 label1:label1value、label2:label2value 并在服务器端提取它们。 asp.net 使用相同的原理来维护视图状态
猜你喜欢
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-18
  • 2016-11-17
  • 2012-04-04
相关资源
最近更新 更多