如何在使用JQuery显示弹出窗口时防止在asp按钮上回发

How to prevent postback on asp button while displaying a popup using JQuery

本文关键字:asp 按钮 JQuery 显示 窗口      更新时间:2023-09-26

我的GridView中有以下ItemTemplate

<ItemTemplate>
    <asp:Button UseSubmitBehavior="false" runat="server" ID="btnShow" CssClass="btnSearch" Text="View All" CommandName="ViewAll" OnClientClick="myfunction(); return false;" OnCommand="btnShow_Command" CommandArgument='<%#((GridViewRow)Container).RowIndex%>' />
</ItemTemplate>

对于ItemTemplate,我有一个按钮,当使用以下JQuery点击时会打开一个弹出窗口:

$(document).ready(function () {
    $(".btnSearch").click(function (e) {
        e.preventDefault();
        //centering with css
        centerPopup();
        //load popup
        loadPopup();
    });
});
function myfunction() {
}

我的Command代码背后:

protected void btnShow_Command(object sender, CommandEventArgs e)
        {
            int index = 0;
            if (e.CommandName == "ViewAll")
            {
                index = Convert.ToInt32(e.CommandArgument);
                DataTable cacheTable = HttpContext.Current.Cache["ResultsTable"] as DataTable;
                string column = cacheTable.Rows[index].Field<string>("Guideline");
                string test = BookingResults.Rows[index].Cells[7].Text;
                string html = HttpUtility.HtmlDecode(column);
                ResultsDiv.InnerHtml = html;
                //tbGL.Text = html;
                //upData.Update();
                //MessageBox.Show(index.ToString());
            }
        }

我添加了OnClientClick="myfunction(); return false;",因为每次单击它都会进行回发。如果我有多行,它只在我第一次点击时起作用,但之后的任何时候,当点击另一个或相同的按钮时,弹出窗口都不会显示。

我该如何解决它,以便无论单击哪个按钮,都会显示弹出窗口而不进行回发?

实际上,您还没有显示方法myfunction()的实现,如果my function()方法有任何语法错误,则OnClientClick事件将无效,它将向服务器发回/提交表单。

尝试从OnClientClick中删除调用,并使用类选择器在点击事件上实现您的逻辑,如下所示

$(document).ready(function () {
        $(".btnSearch").click(function (e) {
            e.preventDefault();
            alert($(this).val() + " Clicked"); // you can put your method mymethod() here 
            // you can put youe popup logic here
            return false; 
        });
    });

您还可以看到这个js-fiddle 的例子

把它放在标签上或<%:Html.BeginForm%>标记

OnClientClick="return myfunction(); 
function myfunction(){
// you can put youe popup logic here 
    return false;
}

像这样使用你的按钮永远不会回邮。