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

时间:2014-01-24 05:37:33

标签: c# javascript html 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();


    }

12 个答案:

答案 0 :(得分:18)

添加OnClientClick="return false;"

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

或CodeBehind:

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

答案 1 :(得分:4)

当您使用asp:Button作为服务器控件时,回发将会发生以避免html按钮,

asp:Button .... />

输入

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

答案 2 :(得分:4)

当进行服务器访问时页面被刷新,并且默认情况下按钮等服务器控件具有属性 AutoPostback = true ,这意味着无论何时单击它们都会访问服务器将被制作。 为插入按钮设置 AutoPostback = false ,这将为您提供帮助。

答案 3 :(得分:3)

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

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

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

答案 4 :(得分:2)

在页面声明中设置MaintainScrollPositionOnPostBack="true"

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

答案 5 :(得分:1)

HTML

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

的javascript

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

答案 6 :(得分:1)

您可以使用为asp.net制作的“ASP.net AJax Control toolkit” http://www.ajaxcontroltoolkit.com/

答案 7 :(得分:0)

我想我也遇到了这个问题,单击按钮后我试图让日历显示,但点击按钮后页面仍然保持刷新

MaintainScrollPositionOnPostBack="true"

这实际上回答了我的问题。

我不能投票或评论,我今天刚加入SO

答案 8 :(得分:0)

在执行实际的button_click事件之前,按钮在刷新页面时遇到了相同的问题(因此必须将按钮单击两次)。 在server.transfer-command(server.transfer(“ testpage.aspx”))之后发生此行为。

在这种情况下,解决方案是将server.transfer-command替换为response-redirect(response.redirect(“ testpage.aspx”))。

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

答案 9 :(得分:-1)

您可以使用Ajax来阻止页面刷新

答案 10 :(得分:-1)

当必须向下滚动网格视图以选择行时,<?php session_start(); ?> <?php header('Content-Disposition: attachment; filename="befizetesek.csv"'); $hostname = "localhost"; $dbusername = "username"; $dbname = "dbname"; $dbpassword = "password"; $dbhandle = ($GLOBALS["___mysqli_ston"] = mysqli_connect($hostname, $dbusername, $dbpassword)) or die("Nem sikerült kapcsolódni az adatbázishoz"); $selected = ((bool)mysqli_query($dbhandle, "USE " . $dbname)) or die("Nincs kiválasztva adatbázis tábla"); $query ="SELECT VU.first_name AS 'Befizeto neve', VU.email AS 'Befizeto tagkodja', VI.order_item_name AS 'Befizetett idoszak', VO.order_total AS 'Befizetett osszeg', VO.created_on AS 'Befizetes datuma', VO.order_number AS 'Befizeto azonosito' FROM m1uzl_virtuemart_orders VO INNER JOIN m1uzl_virtuemart_order_items VI ON VO.virtuemart_order_id = VI.virtuemart_order_id INNER JOIN m1uzl_virtuemart_order_userinfos VU ON VI.virtuemart_order_id = VU.virtuemart_order_id WHERE VO.order_status='C' AND (VO.created_on >= STR_TO_DATE ('" . $_SESSION["tol"] . "', '%Y-%m-%d') AND VO.created_on <= STR_TO_DATE ('" . $_SESSION["ig"] . "', '%Y-%m-%d'))"; $export = mysqli_query($GLOBALS["___mysqli_ston"], $query ) or die ( "Sql error : " . ((is_object( )) ? mysqli_error( ) : (($___mysqli_res = mysqli_connect_error()) ? $___mysqli_res : false)) ); $fields = (($___mysqli_tmp = mysqli_num_fields( $export )) ? $___mysqli_tmp : false); for ( $i = 0; $i < $fields; $i++ ) { $header .= ((($___mysqli_tmp = mysqli_fetch_field_direct( $export , $i )->name) && (!is_null($___mysqli_tmp))) ? $___mysqli_tmp : false) .";" ; } while( $row = mysqli_fetch_row( $export ) ) { $line = ''; foreach( $row as $value ) { if ( ( !isset( $value ) ) || ( $value == "" ) ) { $value = ""; } else { $value = str_replace( ';' , ';' , $value ); $value = ';' . $value ; } $line .= $value; } $data .= trim( $line ) . "\n"; } $data = str_replace( "\r" , "" , $data ); if ( $data == "" ) { $data = "\n(0) Nincs találat!\n"; } header("Content-type: application/octet-stream"); header("Pragma: no-cache"); header("Expires: 0"); print "$header\n$data"; ?> 将使其继续显示该行之后选择它。

答案 11 :(得分:-1)

单击按钮后事件完成您的任何任务...最后一行复制并粘贴...正在正常工作... Asp.Net中的C#

Page.Header.Controls.Add(new LiteralControl(string.Format(@“ ”,Request.Url.AbsoluteUri)));