简体   繁体   中英

hidden variable does not have value after postback asp.net

I have following

<input type="hidden" id="hdnField" name="hdnField"/>

Request.Form.Set("hdnField", x.ToString());

after the page post back the value is not there.

I am new to this, any help would be appreciated.

Source:

You could define a property in your page class and then modify the property value in your code:

    protected string HiddenFieldValue { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
            HiddenFieldValue = x.ToString();
        else
            HiddenFieldValue = x.ToString();
    }

Then define the hidden form field like this so that it's value is set to the property value:

    <input type='hidden' id='hdnField' value='<%=HiddenFieldValue %>' />

If you only want to set the value form the property during a postback or non-postback you could add the condition as well:

    <input type='hidden' id='hdnField' value='<% if(IsPostBack) { %> <%=HiddenFieldValue%> <% } %>' />

You should use asp:HiddenField tag provided by asp rather than using the basic HTML input.

<asp:HiddenField ID="hdnField" Value="" runat="server" ClientIDMode="Static" />

Using this, you can read and write value in c# using hdnField.Value and in jQuery using $('#hdnField').val() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM