开发者

Is this the intended behavior of textbox and label?

I set the value of the controls when the D开发者_开发百科OM loads. I have this super simple code on aspx page:

 <script type="text/javascript">
        $(document).ready(function () {
            $('#<%=textBox2.ClientID %>').val($('#<%=textBox1.ClientID %>').val());
            $('#<%=lblVal.ClientID %>').html($('#<%=textBox1.ClientID %>').val());

        });
    </script>

        <asp:TextBox runat="server" ID="textBox1" Text="Test data" />
        <asp:TextBox runat="server" ID="textBox2" />
        <asp:Label runat="server" ID="lblVal" Text="Old Data" />
        <asp:Button runat="server" Text="Click Me" onclick="Unnamed1_Click" />

In my button click event handler I have this code:

protected void Unnamed1_Click(object sender, EventArgs e)
    {
        Debug.Write(textBox2.Text);
        Debug.Write(lblVal.Text);
    }

The thing that came shocking to me lblVal has it's old value. Setting value in javascript doesn't really have any effect on label whereas the textbox2's data is reflected on the server. Is the intended behavior of textbox and label? This came as a bit of surprise to me because I never came across this thing previously.


The label will get rendered to an HTML label tag, not a form field. Therefore it does not have a value that is posted when the form is submitted, and the value you get restored in the postback is from ViewState. Form fields (e.g. a ASP TextBox which becomes an input) will post their value and this will override the value in viewstate.

You could get around this by instead having a hidden input which you update with javascript, and then in your postback update the label with the contents of that instead.


An asp:Label control renders to a span, and is therefore not a form element, and its changed contents will not be posted to the server.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜