Some questions about ASP.Net Postback
Lets say I have a text box which should have a default value.... and it is in an initializing function like so:
void InitializeControls()
{
myTextBox.Text = "Default Text";
}
Now, lets say that I have a button, which does a postback... I want to save the user entered value of the textbox off somewhere in the button's OnClick event.
My question is, when should I call the initializing control code above? I'm thinking it should be in the OnLoad function, however this seems like that I will overwrite the postback data everytime:
protected override void OnLoad(EventArgs eventArgs)
{
base.OnLoad(eventArgs);
Initial开发者_如何学编程izeControls();
}
Will the postback data overwrite my default text above if I have the initializing code in the OnLoad?
Thanks
The user-entered value of the textbox will be lost during the postback if you set the text manually by calling InitializeControl() in Page_Load.
(source: microsoft.com)
Per durilai's comment, place inside a !IsPostBack
if-block the code that you want to happen only when the page loads for the first time:
if (!IsPostBack) {
InitializeControls();
}
Call InitializeControls()
in the OnInit
, before the call to base.OnInit()
. In this way your default value will not be part of the ViewState and you will not be passing it to the client and back for no reason.
You could also just set the default value in the mark-up (in the .aspx file).
Do not call InitializeControls() in PageLoad / OnLoad since this will add the default value to ViewState, bloating ViewState for no reason.
Read the article TRULY understanding ViewState to get a good understanding of this stuff.
I think you are probably looking for the code
if (!Page.IsPostBack)
Which allows you to deal with those things that should only happen on first load.
You could also just set the default value in the textbox in your markup, then you wouldn't need to worry about setting default values in your code and checking for a post back. Otherwise, Page_Load and OnLoad are both appropriate places to set the default values. You'll want to check if the page has posted back, and if so, don't overwrite the user's value:
if (!IsPostBack)
InitializeControls();
精彩评论