Unable to read hidden field value from server side

I have an aspx page (default.aspx) inside which I load a user control (tree.ascx).

inside tree.ascx there is a hidden field.

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

I am assigning a value to a hidden field using javascript.

document.getElementById('<%=HiddenField1.ClientID%>').value = "some text here";
alert(document.getElementById('<%=HiddenField1.ClientID%>').value);
document.getElementById('form1').submit(); 

A warning displays the value absolutely accurately. which means that the value is correctly inserted into the hidden field.

But when I send back to the server and check the value, it is always zero.

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // do something.
        }
        else
        {                
            string str = this.HiddenField1.Value;              
        }
    }

My code always gets an empty line here. somehow postback removes the value from the hidden field.

What could be the reason?

+3
source share
3 answers

Try using the syntax below. It works for me even after the postback.

Aspx code

<asp:HiddenField runat="server" ID="aspHiddenField" />
<input type="hidden" id="inputHidden" value='<%= aspHiddenField.ClientID %>' />

JavaScript code

var inputHidden = document.getElementById('inputHidden');
$("#" + inputHidden.value).val("some text");

if (!string.IsNullOrEmpty(aspHiddenField.Value))
 {
//Your code goes here
}
+1

, , , , 1- - > , .

0

Put your hidden field in the update panel, for example:

<asp:UpdatePanel ID="UpnlHidden" runat="server">
<ContentTemplate>
<asp:HiddenField ID="HiddenField1" runat="server"/>
</ContentTemplate>
</asp:UpdatePanel>

This will work for you :-)

0
source

All Articles