Как избежать обновления страницы после события нажатия кнопки в asp.net

Это следующий код: страница обновляется, как только завершается событие клика btninsert. Я хочу остановить обновление страницы после нажатия кнопки btninsert

<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>

и это Edit.aspx.cs, в котором у меня есть метод

    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();


    }

Ответ 1

Добавить OnClientClick="return false;",

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

или в CodeBehind:

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

Ответ 2

Поскольку вы используете asp:Button, который является серверным элементом управления, будет отправлено сообщение, чтобы избежать перехода на кнопку html,

asp:Button .... />

Введите

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

Ответ 3

Страница обновилась, когда была выполнена поездка на сервер, а серверные элементы управления, такие как Кнопка, имеют свойство AutoPostback = true по умолчанию, что означает, что каждый раз, когда нажимается на сервер будет выполнен. Установите AutoPostback = false для кнопки вставки, и это поможет вам.

Ответ 4

если у вас есть коды в методе Page_Load, и вы не хотите, чтобы те, которые выполняются после нажатия кнопки, используют, если (! IsPostBack) на странице_Load

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

asp: Button - это серверный элемент управления, а для отправки запроса на сервер и получение обновления страницы необходимости ответа. Вы можете использовать JQuery и Ajax для предотвращения полного обновления страницы

Ответ 5

Задайте MaintainScrollPositionOnPostBack="true" в объявлении страницы:

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

Ответ 6

HTML

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

Javacript

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

код

 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

Ответ 8

Вы можете использовать Ajax для предотвращения обновления страницы

Ответ 9

Я думаю, что у меня также есть эта проблема, я пытался сделать календарь видимым после нажатия кнопки, но страница продолжает обновляться после нажатия кнопки

MaintainScrollPositionOnPostBack="true"

Это действительно ответило на мою проблему.

Я не могу голосовать или комментировать, я просто присоединился к SO сегодня

Ответ 10

Когда вам нужно прокрутить сетку, чтобы выбрать строку, MaintainScrollPositionOnPostBack="true" заставит ее продолжать показывать эту строку после ее выбора.