asp.netbuttonpostback

Disable page refresh after button click ASP.NET


I have an asp button that looks like this:

Default.aspx

<asp:button id="button1" runat="server" Text="clickme" onclick="function" />

Default.aspx.cs

protected void function(object sender EventArgs e)
{
    // Do some calculation
}

However, whenever I press the button, the entire page gets refreshed. I have looked on this site and found many solutions, but none of them really works for my project. Here are some of the suggested solutions:

  1. set onclick="return false;" // but then how do I run the function in the code-behind?
  2. use !IsPostBack in Page_Load // but the page still refreshes completely. I don't want Page_Load to be called at all.
  3. Disable AutoEventWireup. // making this true or false doesn't make a difference.

Does anyone have a solution to this, or is it really impossible?


Solution

  • I would place the control inside of an Update panel. To do so, you would also need a script manager above it, so something like this:

     <asp:ScriptManager runat="server" ID="sm">
     </asp:ScriptManager>
     <asp:updatepanel runat="server">
     <ContentTemplate>
     <asp:button id="button1" runat="server" Text="clickme" onclick="function" />
     </ContentTemplate>
     </asp:updatepanel>
    

    if a control inside the update panel does a postback, it will only reload the part of the page inside of the upate panel.Here is a link you may find useful from the MSDN site.