The hidden field is null !! IsPostBack, not null on IsPostBack

First I will apologize for the vague title of my question. I wasn't sure how to summarize my problem in the title.

I have a hidden field in my .aspx

<input type="hidden" name="hid1" value="0" />

      

I want to set the value of this field during a page load event and if it is not a postback.

protected void Page_Load(object sender, EventArgs e) {
    if (!Page.IsPostBack) {

        // This doesn't work!
        Request.Form["hid1"] = "1";

    }

    if (Page.IsPostBack) {

        // This DOES work!
        Request.Form["hid1"] = "1";

    }
}

      

The problem is that the request does not contain a hidden field in the Form array during the page load event when it is not postback (i.e. the first time the page is clicked). Subsequent calls to the page (i.e. - postbacks) result in the Form array containing the hidden field.

I'm sure this has to do with the page lifecycle, but I really need to know how to set a hidden field during a page load event and when is it not postback?

EDIT: I really, really don't want to include the runat = "server" attribute!

+2


source to share


5 answers


You can define a property in your page class and then change the property's value in code:

    protected string HiddenFieldValue { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
            HiddenFieldValue = "postback";
        else
            HiddenFieldValue = "not postback";
    }

      

Then define the hidden form field so that it is set to the property value:



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

      

If you only want to set the shape of the value on the property during postback or without postback, you can also add a condition:

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

      

+4


source


Try converting the input to an element HiddenField

(or at least an runat="server"

input
) and referring to it using an ID, not via Request.Form

.



+2


source


Instead:

<input type="hidden" name="hid1" value="0" />

      

try this:

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

      

Then in Page_Load()

hid1.Value = "whatever...";

      

It will show up both before and after postback when you declare it this way.

+2


source


Why don't you make it a server by setting "runat =" server "" on the input control? It will then be available from your code behind and you can set the value during the first page load.

+1


source


why don't you access this field through the style class and use the runat = server?

+1


source







All Articles