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!
source to share
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%> <% } %>' />
source to share
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
.
source to share