Some questions about ASP.Net Postback

£可爱£侵袭症+ 提交于 2020-01-15 05:14:31

问题


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);

    InitializeControls();
}

Will the postback data overwrite my default text above if I have the initializing code in the OnLoad?

Thanks


回答1:


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.




回答2:


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();
}



回答3:


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.




回答4:


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();


来源:https://stackoverflow.com/questions/2471294/some-questions-about-asp-net-postback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!