开发者

to avoid page refresh during button click event in asp.net

public partial class _Default : System.Web.UI.Page 
{
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)  // If page loads for first time
    {
        Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());   // Assign the Session["update"] with unique value

        //=============== Page load code =========================





        //============== End of Page load code ===================
    }

}



protected void Button1_Click(object sender, EventArgs e)
{
    if (Session["update"].ToString() == ViewState["update"].ToString())    // If page not Refreshed
    {
        //=============== On click event code =========================

        Label1.Text = TextBox1.Text;
        //lblDisplayAddedName.Text = txtName.Text;


        //=============== End of On click event code ==================

        // After the event/ method, again update the session  
        Session["update"] = Server.Url开发者_C百科Encode(System.DateTime.Now.ToString());
    }
    else  // If Page Refreshed
    {
        // Do nothing 
    }
}
protected override void OnPreRender(EventArgs e)
{
    ViewState["update"] = Session["update"];
}

}

This is not working for high resolution gradient background.


Consider wrapping your button and the label in an updatepanel control, which uses AJAX to refresh their contents. The rest of the page will not be reloaded and the action will not affect the browser navigation.

See this page on how an updatepanel control works.


Since you are handling the button click event in server side there has to be a postback to handle it.

If you do not want a post back to happen change the event handling to "client click"


//Heinzi code worked for me just made a small change in OnPreRender event, assign the ViewsState value when its not post back

protected override void OnPreRender(EventArgs e)
    {
        if (!IsPostBack)
        {
            ViewState["update"] = Session["update"];

        }

    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜