First I'll apologize for the unclear title of my question. I wasn't sure how to succinctly describe my problem in a 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 the 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 doesn't contain the hidden field in the Form array during the page load event when it's not a postback (ie - the first time the page is hit). Subsequent hits to the page (ie - postbacks) result in the Form array containing the hidden field.
I'm sure that it has to do with the lifecycle of the page, but what I really need to know is how do I set the hidden field during the page load event and when it is not a postback?
EDIT:
I really, really don't want to incorporate the runat="server" attribute!
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 = "postback";
else
HiddenFieldValue = "not postback";
}
Then define the hidden form field like this so that it's value is set to the property value:
<input type='hidden' id='hidden1' 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='hidden1' value='<% if(IsPostBack) { %> <%=HiddenFieldValue%> <% } %>' />
Try converting the input into a HiddenField control (or, at least, a runat="server" input), and reference it by it's ID, rather than through Request.Form.
Instead of:
<input type="hidden" name="hid1" value="0" />
try this:
<asp:HiddenField runat="server" ID="hid1" />
Then in your Page_Load()
hid1.Value = "whatever...";
It will be visible both before and after postback when you declare it in this manner.
Why don't you make it a server control by setting 'runat="server"' on the input control? Then it will be accessible from your code behind, and you will be able to set the value during the first page load.
why dont you access that field through a style class and use runat server=?
Related
I'm using an aspx file as my main page with the following code snippet:
<input type="text" runat="server" id="Password" />
<asp:Button runat="server" id="SavePassword"
Text="Save" OnClick="SavePassword_Click"/>
Then in the code behind I use:
protected void SavePassword_Click(object sender, EventArgs e)
{
string a = Password.Value.ToString();
}
Setting Password.Value in the Page_Load works as expected, but setting a to the value results in an empty string in a regardless what I type in on the page befoere I click the save button.
Am I overlooking here something?
You should add label field with name labelShow in aspx page like this
<asp:Label ID="labelShow" runat="server"></asp:Label>
Then add the string into .cs file
protected void SavePassword_Click(object sender, EventArgs e)
{
string a = Password.Value.ToString();
labelShow.Text = a.ToString();
}
I can figure several errors :
You say something about Page_Load. You should always remember Page_Load is executed at every postback. So if you write something into the textbox at Page_Load, it will erase the value typed by user. You can change this behavior by veriyfing
if(!IsPostBack)
{
// Your code
}
around your Page_Load content.
input runat="server" is not the proper way to do TextBox in ASP.Net, in most cases you should use asp:TextBox
You don't do anything with your "a" string, your current code sample does nothing, whether the Password field is properly posted or not. You can do as suggested by Ravi in his answer to display it.
I suggest you to to learn how to use VS debugger, and to read a good course on ASP.Net Webforms to learn it.
I've just written a ASP .NET wrapper for jQuery UI control as user control. It can be used like this:
<ui:DatePicker ID="startDate" runat="server" LabelText="Start Date:" />
Currently I set initial value of this control in Page_Load handler, just like this:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
startDate.Value = DateTime.Now.AddMonths(-2);
}
}
But I thought that it would be nice to move initialization code to markup. Yet I can't work out is how to set initial value of this control using inline tag, for instance:
<ui:DatePicker ID="startDate" Value='<%= DateTime.Now.AddMonths(-2) %>' runat="server" LabelText="Start Date:" />
I have a property:
public DateTime? Value
{
get
{
DateTime result;
if (DateTime.TryParse(dateBox.Text, out result))
{
return result;
}
return null;
}
set
{
dateBox.Text = value != null ? value.Value.ToShortDateString() : "";
}
}
I've tried different inline tags combinations, and I always get a compilation error. Is there a way to achieve it with inline tags?
You will need to put the actual date representation in the property. The reason is that some properties of Asp.Net controls also behave like that e.g. the visible property of a TextBox cannot be set like <asp:TextBox runat="server" Visible='<%= true %>'></asp:TextBox>
<ui:DatePicker ID="startDate" Value='20/10/2012' runat="server" LabelText="Start Date:" />
Or set the value from your Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
startDate.Value = DateTime.Now; //initialize DatePicker
}
}
I found these link:
Why will <%= %> expressions as property values on a server-controls lead to a compile errors?
Set Visible property with server tag <%= %> in Framework 3.5
i created a user control with a custom property in the asp.net like the following. In the aspx page that uses this user control i have something like the following. The user control is in a FormView's EditItemTemplate
<uc1:MyControl ID="c1" runat="server" CountryCode='<%# this.DropDownCountry.SelectedValue %>' Value1='<%# Bind("Value1Col") %>' />
I am trying to use the CountryCode in the Page_Load method of the user control, but the value has not be populated.
My question is at which stage in the control's life cycle does the bounded value gets populated? I tried assigning value directly like the following and it does get its value at the Page_Load method.
<uc1:MyControl ID="c1" runat="server" CountryCode="CA" Value1='<%# Bind("Value1Col") %>' />
thanks,
the uc1:MyControl has the following property:
[Browsable(true)]
[Bindable(true, BindingDirection.TwoWay)]
[DefaultValue(0)]
[PersistenceMode(PersistenceMode.Attribute)]
public string CountryCode
{
get { return _countryCode; }
set { _countryCode = value; }
}
Since you're using databinding syntax you need to call DataBind method on your control - you can add this to the Page_Load method of the aspx page like so:
protected void Page_Load(object sender, EventArgs e)
{
c1.DataBind();
}
Setting value in html control in code behind without making server control
<input type="text" name="txt" />
<!--Please note I don't want put 'runat="server"' here to get the control in code behind-->
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
Code behind:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//If I want to initlize some value in input, how can I set here
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Request["txt"] // Here I am getting the value of input
}
This answer comes from memory, so I apologize if it's slightly off.
What you can do is use an ASP.NET inline expression to set the value during the loading of the page.
First, add a property in the code-behind of your page.
protected string InputValue { get; set; }
In the Page_Load event, set the value of the property.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.InputValue = "something";
}
}
Finally, add an inline expression in your page markup like this:
<input type="text" name="txt" value="<%= this.InputValue %>" />
This will let you set the value of the input element without making it a server-side tag.
Elements that are not set runat="server" are considered plain text and collected into as few Literal objects as possible (one between each serverside control). I suppose if you really really wanted to, you could try to find the correct Literal (or maybe LiteralControl) object in Page.Controls, and modify it, but I'd definately recommend against it.
What's so terrible about setting it runat="server" ?
And yes, of course you can also use <%= %>. Embedded code blocks. They're evaluated at Render time, so it should be relatively safe to do so.
Add an expression in your page like this:
<input class="field" id="locality" name="loc" value="<%= this.inputtypeCT %>"/>
Add a property in the code-behind of your page:
protected string inputtypeCT;
In the Page_Load event, set the value of the property:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.inputtypeCT = "test"
}
}
<input type="text" name="txt" value="<%= System.Web.HttpUtility.HtmlEncode(this.InputValue) %>" />
Add runat server
or use Asp controls like below
<asp:TextBox type="text" runat="server" class="demoHeaders" id="datepicker" ClientIDMode="Static" Text=""/>
Also make sure that you used ClientIDMode="Static" for the naming of control to be in clinet as like server.
Enjoy!
I have a drop down list holding some choices. Based on user selection I need to create some dynamic controls and render them on the form.
My understanding is that dynamic controls need to be created in OnInit or in CreateChildControls so that the ViewState for these dynamic controls is restored correctly by the runtime.
The problem is, I am unable to get the SelectedValue of the dropdown in OnInit or CreateChildControls since the ViewState has not been restored for the dropdown as yet.
Is there any way to obtain the current selection so that I can create the dynamic controls based on the current user selection and add them the page correctly
EDIT:
The markup looks as follows:
<form id="form1" runat="server">
<div>
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" AppendDataBoundItems="true">
<asp:ListItem Text="(Select Color)" Value="" />
<asp:ListItem Text="Red" Value="Red" />
<asp:ListItem Text="Green" Value="Green" />
<asp:ListItem Text="Blue" Value="Blue" />
</asp:DropDownList>
<asp:PlaceHolder ID="plHolder" runat="server" />
</div>
</form>
and here is the code behind:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected override void CreateChildControls()
{
base.CreateChildControls();
TextBox tb = new TextBox();
if (ddl.Text != "")
{
tb.Text = ddl.Text;
if (Session["id"] != null)
{
string id = Session["id"].ToString();
tb.ID = id;
}
else
{
Session["id"] = tb.ID = Guid.NewGuid().ToString().Replace("-", "");
}
plHolder.Controls.Add(tb);
}
}
}
On the line "tb.Text = ddl.Text;" I'm hoping to get the current selection and based on that set the value of the text property for the dynamic control. But the current selection has not been set yet since it's in OnInit.
If the controls really need to be created in OnInit or CreateChildControls then one thing you can do is get the value of your static control from the Request.Form[] collection during OnInit.
So instead of doing:
string selected = myDropDown.SelectedValue;
you do
string selected = Request.Form[myDropDownUniqueID];
... where myDropDownID is the 'unique id' assigned to myDropDown. Note that usually this will be the same as the 'id' assigned to the control, unless it is inside a control container.
This is effectively pulling the value straight out of the HTML Form data that gets sent to the server, rather than waiting for ASP.NET to unpack it into the properties of the control.
In one of my projects I add controls dynamically in Page_Load.
I use SaveControlState and LoadControlState to manually save and load the control view state.
http://msdn.microsoft.com/en-us/library/system.web.ui.control.loadcontrolstate.aspx
Shay.