How do I increment a step value to be processed when the page loads in ASP.NET?

偶尔善良 提交于 2019-12-08 08:04:22

问题


How do I increment a step value to be processed when the page loads? For example, in the code below the viewstate variable is not incremented until after Page_Load, due to the ASP.NET page lifecycle.

protected void Page_Load(object sender, EventArgs e)
{
    switch ((int)ViewState["step"])
    {
        //do something different for each step
    }
}

protected void btnIncrementStep_Click(object sender, EventArgs e)
{
    //when the button is clicked, this does not fire 
    //until after page_load finishes
    ViewState["step"] = (int)ViewState["step"] + 1;
}

回答1:


Just move the switch statement into an event that happens later. E.g. LoadComplete() or PreRender(). PreRender is probably a bit late, depending on what you want to do.




回答2:


There's no way around this. Page_Load event will always happen before any control events get fired. If you need to do something after the control event, use Page_PreRender.

ASP.Net Page Lifecycle Image




回答3:


Increment during the LoadComplete event or even during OnLoad.

You have all the information needed to make the decision whether to increment from the form data. You don't need to wait for the onClick() event. Check the form to see if the item will be clicked.

Look in the request.params("__EVENTARGS")

This identifies the control that caused the postback.




回答4:


If you need to increment and check the value during Page_Load, then an option would be to store the value in the session instead of ViewState, e.g:

private int Step
{
  get { return (int)Session["step"]; }
  set { Session["step"] = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
       Step = 0; // init
    else
       Step ++; // increment

    switch (Step)
    {
        //do something different for each step
    }
}


来源:https://stackoverflow.com/questions/418596/how-do-i-increment-a-step-value-to-be-processed-when-the-page-loads-in-asp-net

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