如何在ASP.NET中避免按钮点击事件后页面刷新

22

以下是代码,页面在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();


    }

4
你为什么想要停止页面刷新? 如果这样做,那么你的SqlCommand将不会被执行... 你是想保留页面的值吗? - Viral Jain
6个回答

24

添加 OnClientClick="return false;"

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

或者在 CodeBehind 中:

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

3
它也不会调用该函数。 - Zeeshan Ahmad Khalil
1
这个可以工作。应该标记为解决方案。然而,为了减少混淆,示例应包括函数:<asp:button ID =“btninsert” runat =“server” text =“Button” onClick =“{您的函数放在这里}”OnClientClick =“return false;”/> - NegativeFeedbackLoop
1
@NegativeFeedbackLoop,如果包括 onClick 函数并不重要。如Zeeshan的评论所说,在 OnClientClick 属性中添加 return false 将防止调用该函数,因此它与根本没有该函数是一样的。 - TylerH

9

如果您在Page_Load方法中有一些代码,并且您不希望这些代码在按钮单击后执行,请在Page_Load上使用if(!IsPostBack)。

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

asp:Button是一个服务器控件,用于向服务器发送请求并获取响应时需要刷新页面。您可以使用JQuery和Ajax来避免完全刷新页面。


9

由于您正在使用服务器控件asp:Button,因此会发生回传以避免这种情况,请改用html按钮。

asp:Button .... />

输入

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

5
当向服务器发送请求时,页面会被刷新,而像按钮这样的服务器控件默认具有属性AutoPostback = true,这意味着每当它们被单击时都会向服务器发送请求。 将AutoPostback = false设置为插入按钮,这将为您解决问题。

1
坦白说,如果AutoPostback = false的按钮被冻结了,也就是说除非您在其单击事件中发送Ajax调用,否则它无法执行任何操作。请检查您的按钮是否位于另一个服务器控件内?如果是,则该控件将负责页面刷新。 - Zeeshan Ajmal

2
在页面声明中设置 MaintainScrollPositionOnPostBack="true"
<%@ Page Language="C#" MaintainScrollPositionOnPostBack="true" Title="Home" %>

11
楼主表示想停止页面刷新,而不是记住滚动位置。为什么会有这样的建议呢? - Kritner
这并没有回答问题。 - TylerH

0

我曾经遇到过同样的问题,即在执行实际的button_click事件之前,按钮会刷新页面(因此需要点击两次按钮)。 这种行为发生在server.transfer命令(server.transfer("testpage.aspx"))之后。

在这种情况下,解决方案是用response-redirect(response.redirect("testpage.aspx"))替换server.transfer命令。

有关这两个命令之间差异的详细信息,请参见Server.Transfer Vs. Response.Redirect


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接