Implementation of IsPostBack in page load

后端 未结 8 1000
你的背包
你的背包 2020-12-06 00:07

The more I use ASP.NET, the more if (!IsPostBack) {} seems pointless...

First example:

For example, I just Googled an issue, they said use this

相关标签:
8条回答
  • 2020-12-06 00:43

    In short, you use it everytime you need to execute something ONLY on first load.

    The classic usage of Page.IsPostBack is data binding / control initialization.

    if(!Page.IsPostBack)
    {
       //Control Initialization
       //Databinding
    }
    

    Things that are persisted on ViewState and ControlState don't need to be recreated on every postback so you check for this condition in order to avoid executing unnecessary code.

    Another classic usage is getting and processing Querystring parameters. You don't need to do that on postback.

    0 讨论(0)
  • 2020-12-06 00:48

    Your event handlers should be wired up whenever the event can be fired (irrespective of PostBack status)

    Also, when adding controls dynamically, be sure to observe the asp page lifecycle

    0 讨论(0)
  • 2020-12-06 00:48

    Also, you must use IsPostBack if you want to initialize controls, otherwise they will be reverted to the default on every load. This will confuse the user as when they try to use the form their entered values will get reset to your defaults.

    0 讨论(0)
  • 2020-12-06 01:00

    It's for processing form data.

    If you want to handle POSTed data, you only want to do so if the page actually posted data, not on first load. Hence, the IsPostBack flag.

    0 讨论(0)
  • 2020-12-06 01:00
    protected void Page_Load(object sender, EventArgs e)            
    {
        if (!IsPostBack) { 
            SqlConnection conn = new SqlConnection("Data Source=-----; Database=-----; Integrated Security=True");
            SqlDataAdapter da = new SqlDataAdapter();
            conn.Open();
            da.SelectCommand = new SqlCommand("Select Command",conn);
            conn.Close();
            DataTable dt = new DataTable();
            da.Fill(dt);
    
            ddlSearch.DataSource = dt;
            ddlSearch.DataTextField = "---";
            ddlSearch.DataValueField = "---";
            ddlSearch.DataBind();
        }
    }
    
    0 讨论(0)
  • 2020-12-06 01:02

    What can happen if you cause a postback is you can change the state of your controls, without meaning to. For example in using a gridview, if you postback during edit mode, you will no longer have access to your edit-ed fields.

    Often you need to preserve the information from disapearing on a page when you hit the server, this is the point of

    if(!Page.IsPostBack)
    
    0 讨论(0)
提交回复
热议问题