[c#] How to avoid page refresh after button click event in asp.net

This is the following code the page refreshes as soon as the btninsert click event is completed i want to stop the page refresh after the btninsert is click

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

    <ContentTemplate>


        <div style="margin-bottom: 20px; margin-top: 20px;"><span><strong style="font-size: large;">Edit User</strong></span></div>
        <div>
            <span style="float: left; width: 50%;">&nbsp;</span> <span style="float: left; width: 50%;">
                <span style="width: 100%; float: left; text-align: right;">
                    <asp:Label ID="lblMessage" runat="server" Text="-"></asp:Label></span>
            </span>
        </div>

        <div style="width: 100%; float: left;">
            <hr />
        </div>


        <div style="width: 816px; margin-left: 5px; margin-top: 20px; height: 463px;">

            <div style="width: 100%; float: left; padding-top: 15px; height: 257px; margin-left: 0px;">
                <span class="Divide">
                    <span class="simDivide1">FullName</span>
                    <span class="simDivide">
                        <asp:TextBox ID="txtfullname" runat="server" Width="180px">
                        </asp:TextBox>
                    </span>


                </span>
                <span class="Divide">
                    <span class="simDivide1"></span>
                    <span class="simDivide"></span>
                </span>


                <span class="Divide">
                    <span class="simDivide1">Username</span>
                    <span class="simDivide">
                        <asp:TextBox ID="txtusername" runat="server" Width="180px">
                        </asp:TextBox>
                    </span>
                </span>

                <span class="Divide">
                    <span class="simDivide1"></span>
                    <span class="simDivide"></span>
                </span>

                <span class="Divide">
                    <span class="simDivide1">Password</span>
                    <span class="simDivide">
                        <asp:TextBox ID="txtpassword" runat="server" Width="180px">
                        </asp:TextBox>
                    </span>
                </span>

                <span class="Divide">
                    <span class="simDivide1"></span>
                    <span class="simDivide"></span>
                </span>


                <span class="Divide">
                    <span class="simDivide1">Mobile No
                    </span>
                    &nbsp;<span class="simDivide"><asp:TextBox ID="txtmobileno" runat="server" Width="180px">
                    </asp:TextBox>
                    </span>
                </span>

                <span class="Divide">

                    <span class="simDivide"></span>
                </span>


                <span class="Divide">
                    <span class="simDivide1">Role
                    </span>
                    &nbsp;<span class="simDivide"><asp:TextBox ID="txtrole" runat="server" Width="180px">
                    </asp:TextBox>
                    </span>
                </span>



                <script src="jquery-2.0.2.js"></script>

                <script language="javascript">

                    function done() {
                        var list = document.getElementById("tid");
                        list.removeChild(list.lastChild);


                    }


                    function changecourse(e) {

                        var change = document.getElementById('mytext').value;
                        var i = 1;

                        mNewObj = document.createElement('div');
                        mNewObj.id = "BOX" + i;
                        mNewObj.style.visibility = "show";
                        mNewObj.innerHTML = change + "&nbsp<a href='#' style='text-decoration: none; color:red' onClick='done()'> x </a> ";


                        document.getElementById("tid").appendChild(mNewObj);
                        i++
                        var a = document.getElementById('mytext').selectedIndex;
                        document.getElementById("ContentPlaceHolder1_Hidden1").value = a;
                        //document.getElementById("ContentPlaceHolder1_btninsert").click();

                        deleted();




                    }

                    function yes() {

                        $("#ContentPlaceHolder1_btninsert").click();

                    }


                    //function insert() {

                    //    $.ajax({
                    //        type: "POST",
                    //        url: "Edituser.aspx.cs/insert",

                    //        success: function () { alert('success'); },
                    //        error: function () { alert('error'); }

                    //    });


                    //}


                    function cancel() {

                        var select = document.getElementById('mytext');
                        select.remove(select.selectedIndex);
                    }


                    function deleted() {

                        document.getElementById("mytext").style.display = 'none';
                        document.getElementById("Button1").style.display = 'none';
                        document.getElementById("tid").style.display = 'inline';
                        document.getElementById("mylink").style.display = 'inline';
                    }



                    function showdiv() {

                        document.getElementById("mylink").style.display = 'none';
                        document.getElementById("mytext").style.display = 'inline';
                        document.getElementById("Button1").style.display = 'inline';


                    }


                </script>



            <input id="Hidden1" type="hidden" runat="server" />
            </div>
            <asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Style="margin-left: 5px" Text="Edit" Width="39px" />
            <br>
            <br>

            <asp:UpdatePanel runat="server">
                <ContentTemplate>
           &nbsp&nbsp&nbsp&nbsp<div id="tid" >
                               </div>
            <div id="di">

                <a id="mylink" onclick="showdiv()">Add Depot</a>

                <select id='mytext' name='mytext' style="display: none">
                    <option>--Select--</option>
                    <option>Mumbai</option>
                    <option>Delhi</option>
                    <option>Banglore</option>
                    <option>Ahmedabad</option>
                </select>
               <input type="button" id="Button1" style="display: none" onclick=" changecourse(); yes(); cancel(); return false;" value="add" />
                </div>
            <asp:Button ID="btninsert" runat="server"  Style="display: none" OnClick="btninsert_Click" Text="Insert" ValidationGroup="C" />

                </ContentTemplate>
                </asp:UpdatePanel>
             </ContentTemplate>
</asp:UpdatePanel>

and this is Edit.aspx.cs in which i have method

    protected void btninsert_Click(object sender, EventArgs e)
    {
        string a = Hidden1.Value;
        string UserId = Convert.ToString(Session["LoginId"]);
        con.Open();
        SqlCommand cmd = new SqlCommand("INSERT INTO UserDepot (UserId,DepotId)" +
            "VALUES ('" + UserId + "','" + a + "')", con);
        cmd.ExecuteNonQuery();
        con.Close();


    }

This question is related to c# javascript html asp.net

The answer is


After button click event complete your any task...last line copy and past it...Is's Working Fine...C# in Asp.Net

Page.Header.Controls.Add(new LiteralControl(string.Format(@" <META http-equiv='REFRESH' content=3.1;url={0}> ", Request.Url.AbsoluteUri)));


Page got refreshed when a trip to server is made, and server controls like Button has a property AutoPostback = true by default which means whenever they are clicked a trip to server will be made. Set AutoPostback = false for insert button, and this will do the trick for you.


When one has to scroll down a gridview to select a row, MaintainScrollPositionOnPostBack="true" will make it continue to show that row after one has selected it.


I think I also have this problem, I was trying to make calendar visible after clicking a button but the page keeps refreshing after clicking the button

MaintainScrollPositionOnPostBack="true"

This actually answered my problem.

I cant vote or comment, I just joined SO today


Set MaintainScrollPositionOnPostBack="true" in the page declaration:

<%@ Page Language="C#" MaintainScrollPositionOnPostBack="true" Title="Home" %>

if you have some codes in your Page_Load method and you don't want that those execute after button click use if(!IsPostBack) on Page_Load

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       // put codes here
    }
}

asp:Button is a server control and for send request to server and get response need page refresh. You can use JQuery and Ajax to prevent full Page refresh


html

 "input type ="text" id="txtnothing" runat ="server" "

javacript

var txt = document.getElementById("txtnothing");
        txt.value =  Date.now();

code

 If Not (Session("txtnothing") Is Nothing OrElse String.IsNullOrEmpty(Session("txtnothing"))) Then
            If Session("txtnothing") = txtnothing.Value Then
                lblMsg.Text = "Please try again not a valid request"
                Exit Sub
            End If
        End If
        Session("txtnothing") = txtnothing.Value

Add OnClientClick="return false;" ,

<asp:button ID="btninsert" runat="server" text="Button" OnClientClick="return false;" />

or in the CodeBehind:

 btninsert.Attributes.Add("onclick", "return false;");

I had the same problem with a button doing a page refresh before doing the actual button_click event (so the button had to be clicked twice). This behavior happened after a server.transfer-command (server.transfer("testpage.aspx").

In this case, the solution was to replace the server.transfer-command with response-redirect (response.redirect("testpage.aspx").

For details on the differences between the two commands, see Server.Transfer Vs. Response.Redirect


As you are using asp:Button which is a server control, post back will happen to avoid that go for html button,

asp:Button .... />

Type to

input type="button" .... />

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery