使用asp.net listview删除的SweetAlert确认对话框?

时间:2015-11-04 13:12:08

标签: c# jquery asp.net listview sweetalert

请帮助我理解这一点。

我创建了一个ListView,显示来自SQL数据库的数据。我已启用插入,编辑和删除功能。

我想要什么?

我想使用SweetAlert提示用户确认 / 是否要从ListView中删除该条目。

我做了什么?

首先 我尝试使用“内置”功能,我将OnClientClick="return confirm('are you sure')"添加到调用删除给定ListView条目的<asp:Button/>。那很有效!当我点击是删除它没有删除它。除了添加上述内容之外,我不需要做任何其他事情。 这不是我想要的。我希望显示发烧友SweetAlert,这里问题就出现了。

第二次 我以为我可以简单地创建SweetAlert脚本并从按钮调用其函数名称。但是,当这样做时,它会打开SweetAlert,但在我有机会点击是和否之前,它已经删除了该项并关闭了该框。

<script>
    function deletealert()
    {
        swal({
            title: "Are you sure?",
            text: "You will not be able to recover this imaginary   file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonColor: "#DD6B55",
            confirmButtonText: "Yes, delete it!",
            cancelButtonText: "No, cancel plx!",
            closeOnConfirm: false,
            closeOnCancel: false                   
        },
        function (isConfirm) {
            if (isConfirm) {
                swal("Deleted!", "Your imaginary file has been deleted.", "success");
            } else {
                swal("Cancelled", "Your imaginary file is safe :)", "error");
            }
        });
    }
</script>

现在我知道上面没有任何功能,但我甚至没有机会转到是和否,它自己关闭了脚本。然后我发现我可以通过在删除CausesValidation=false上设置<asp:Button />来停止删除,但之后什么也没发生。

第三 我认为我有一个突破,但我不知道如何完成它。我发现在ListView上有一个名为 ItemDeleting 的事件。在执行删除之前会触发此事件。我测试了它,它可以工作。

protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
    {
        ClientScript.RegisterStartupScript(GetType(), "hwa", "deletealert();", true); //Calls the sweetalert

        e.Cancel = true;
       //e.Cancel = false;
    }

如果我使用e.Cancel = true;,则不会删除该项目并取消操作。如果我使用e.Cancel = false;,则该项目将被删除。所以我想我可能必须将这个功能与上面的jQuery结合起来。我不知道我是否可以将jQuery放在受保护的void中并从那里使用它?

已更新,以包含来自haraman的建议解决方案 以下是整个.aspx页面:

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="forum-front.aspx.cs" Inherits="initial.site.forum_front" EnableViewState="true" EnableEventValidation="true" %>

<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="Content/sweetalert.min.js"></script>

<%--CSS Style Sheets--%>
  <link href="Content/Styles.css" rel="stylesheet" />
  <link href="Content/StylesPanel.css" rel="stylesheet" />
  <link href="Content/sweetalert.css" rel="stylesheet" />

  <%--Java Scripts--%>
    <script>
      function deletealert(ctl) {
        // STORE HREF ATTRIBUTE OF LINK CTL (THIS) BUTTON
        var defaultAction = $(ctl).prop("href");
        // CANCEL DEFAULT LINK BEHAVIOUR
        event.preventDefault();
        swal({
          title: "Are you sure?",
          text: "You will not be able to recover this imaginary   file!",
          type: "warning",
          showCancelButton: true,
          confirmButtonColor: "#DD6B55",
          confirmButtonText: "Yes, delete it!",
          cancelButtonText: "No, cancel plx!",
          closeOnConfirm: false,
          closeOnCancel: false
        }, function(isConfirm) {
          if (isConfirm) {
            swal("Deleted!", "Your imaginary file has been deleted.", "success");
            // RESUME THE DEFAULT LINK ACTION
            eval(defaultAction);
            return true;
          } else {
            swal("Cancelled", "Your imaginary file is safe :)", "error");
            return false;
          }
        });
      }
    </script>

    <asp:Panel ID="Panel1" runat="server" Height="1401px">
      <center>
        <table>
          <tr>
            <td>
              <asp:Button ID="TilForsiden" runat="server" OnClick="TilForsiden_Click" Text="Forsiden" CssClass="button" />
            </td>
            <td>
              <asp:Panel ID="Panel2" runat="server" CssClass="panel panel-default">
                <h1><asp:Label ID="ForumOverskrift" runat="server" CssClass=""></asp:Label></h1>
              </asp:Panel>
            </td>
          </tr>
        </table>
      </center>

      <center>
        <asp:ListView ID="ListView1" runat="server" DataSourceID="SqlDataSource1" InsertItemPosition="LastItem" DataKeyNames="OpslagsID" OnDataBound="SkrivOpslag_Click">

          <AlternatingItemTemplate>
            <tr style="">
              <td>
                <asp:LinkButton OnClientClick="return deletealert(this);" ID="LinkButton1" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
                <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Rediger" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
                <asp:Button ID="AnswerButton" runat="server" CommandName="Answer" Text="Svar" CssClass="btn btn-default btn-xs" OnClick="AnswerButton_Click" />
              </td>
              <td>
                <asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
              </td>
              <td>
                <asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
              </td>
              <td>
                <asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
              </td>
              <td>
                <asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
              </td>

            </tr>
            <tr>
              <td></td>
              <td>
                <asp:TextBox ID="AnswerTextBox" Placeholder="Svar..." runat="server" CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" Visible="false" TextMode="MultiLine" Rows="3" />
              </td>
            </tr>
          </AlternatingItemTemplate>

          <EditItemTemplate>
            <tr style="">
              <td>
                <asp:Button ID="UpdateButton" runat="server" CommandName="Update" Text="Update" CssClass="btn-info" />
                <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Cancel" CssClass="btn-default" />
              </td>
              <td>
                <asp:TextBox ID="IndholdTextBox" runat="server" Text='<%# Bind("Indhold") %>' />
              </td>
              <td>
                <asp:TextBox ID="EmneTextBox" runat="server" Text='<%# Bind("Emne") %>' />
              </td>
            </tr>
          </EditItemTemplate>

          <EmptyDataTemplate>
            <table runat="server" style="">
              <tr>
                <td>No data was returned.</td>
              </tr>
            </table>
          </EmptyDataTemplate>

          <InsertItemTemplate>

            <table>
              <tr>
                <td>
                  <asp:TextBox ID="EmneTextBox" Placeholder="Emne..." runat="server" Text='<%# Bind("Emne") %>' CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" />
                </td>
              </tr>
              <tr>
                <td>
                  <asp:TextBox ID="IndholdTextBox" Placeholder="Skriv her..." runat="server" Text='<%# Bind("Indhold") %>' CssClass="form-control" ToolTip="Skriv dit indhold her" TextMode="MultiLine" Rows="8" Width="500px" />
                </td>
              </tr>
            </table>

            <tr style="">
              <td>
                <asp:Button ID="InsertButton" runat="server" CommandName="Insert" Text="Udgiv" CssClass="btn-info" />
                <asp:Button ID="CancelButton" runat="server" CommandName="Cancel" Text="Ryd" CssClass="btn-default" />
              </td>
              <td></td>

            </tr>
          </InsertItemTemplate>

          <ItemTemplate>
            <tr style="">
              <td>
                <asp:LinkButton OnClientClick="return deletealert(this);" ID="LinkButton2" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
                <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />
                <asp:Button ID="AnswerButton" runat="server" CommandName="Answer" Text="Svar" CssClass="btn btn-default btn-xs" OnClick="AnswerButton_Click" />
              </td>
              <td>
                <asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
              </td>
              <td>
                <asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
              </td>
              <td>
                <asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
              </td>
              <td>
                <asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
              </td>
            </tr>
            <tr>
              <td></td>
              <td>
                <asp:TextBox ID="AnswerTextBox" Placeholder="Svar..." runat="server" CssClass="form-control" ToolTip="Skriv dit emne her" Width="500px" Visible="false" TextMode="MultiLine" Rows="3" />
              </td>
            </tr>
          </ItemTemplate>

          <LayoutTemplate>
            <table runat="server">
              <tr runat="server">
                <td runat="server">
                  <table id="itemPlaceholderContainer" runat="server" border="0" style="" class="table table-striped">
                    <tr runat="server" style="">
                      <th runat="server"></th>
                      <th runat="server">Indhold</th>
                      <th runat="server">BrugerNavn</th>
                      <th runat="server">Postnummer</th>
                      <th runat="server">Emne</th>
                    </tr>
                    <tr id="itemPlaceholder" runat="server">
                    </tr>
                  </table>
                </td>
              </tr>
              <tr>
                <td>
                  <asp:Button ID="SkrivOpslag" runat="server" CommandName="SkrivOpslag" Text="Skriv Opslag" CssClass="btn btn-default btn-xs" OnClick="SkrivOpslag_Click" />
                </td>
              </tr>
              <tr runat="server">
                <td runat="server" style="">
                  <asp:DataPager ID="DataPager1" runat="server">
                    <Fields>
                      <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" FirstPageText="Første Side" ShowLastPageButton="True" LastPageText="Sidste Side" PreviousPageText="Forrige" NextPageText="Næste" ButtonCssClass="btn btn-default" />
                    </Fields>
                  </asp:DataPager>
                </td>
              </tr>
            </table>
          </LayoutTemplate>

          <SelectedItemTemplate>
            <tr style="">
              <td>
                <asp:Button ID="DeleteButton" runat="server" CommandName="Delete" Text="Delete" CssClass="btn btn-default btn-xs" />
                <asp:Button ID="EditButton" runat="server" CommandName="Edit" Text="Edit" CssClass="btn btn-default btn-xs" />
              </td>
              <td>
                <asp:Label ID="IndholdLabel" runat="server" Text='<%# Eval("Indhold") %>' />
              </td>
              <td>
                <asp:Label ID="BrugerNavnLabel" runat="server" Text='<%# Eval("BrugerNavn") %>' />
              </td>
              <td>
                <asp:Label ID="PostnummerLabel" runat="server" Text='<%# Eval("Postnummer") %>' />
              </td>
              <td>
                <asp:Label ID="EmneLabel" runat="server" Text='<%# Eval("Emne") %>' />
              </td>
            </tr>
          </SelectedItemTemplate>
        </asp:ListView>
      </center>

      <asp:SqlDataSource ID="SqlDataSource1" runat="server" EnableViewState="True" ConnectionString="<%$ ConnectionStrings:foradbConnectionString %>" DeleteCommand="DELETE FROM [testOpslagstabel] WHERE [OpslagsID] = @OpslagsID" InsertCommand="INSERT INTO [testOpslagstabel] ([Indhold], [DatoTid], [Reference], [BrugerNavn], [Emne], [Postnummer]) VALUES (@Indhold, GetDate(), @Reference, 'testuser', @Emne, @Postnummer)"
      SelectCommand="SELECT * FROM [testOpslagstabel] WHERE ([Postnummer] = @Postnummer)" UpdateCommand="UPDATE [testOpslagstabel] SET [Indhold] = @Indhold, [DatoTid] = @DatoTid, [Reference] = @Reference, [BrugerNavn] = 'testuser', [Postnummer] = @Postnummer, [Emne] = @Emne WHERE [OpslagsID] = @OpslagsID"
      InsertCommandType="Text">
        <DeleteParameters>
          <asp:Parameter Name="OpslagsID" Type="Int32" />
        </DeleteParameters>
        <InsertParameters>
          <asp:Parameter Name="Indhold" Type="String" />
          <asp:Parameter Name="DatoTid" Type="DateTime" />
          <asp:Parameter Name="Reference" Type="Int32" />
          <asp:Parameter Name="BrugerNavn" Type="String" />
          <asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
          <asp:Parameter Name="Emne" Type="String" />
        </InsertParameters>
        <SelectParameters>
          <asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
        </SelectParameters>
        <UpdateParameters>
          <asp:Parameter Name="Indhold" Type="String" />
          <asp:Parameter Name="DatoTid" Type="DateTime" />
          <asp:Parameter Name="Reference" Type="Int32" />
          <asp:Parameter Name="BrugerNavn" Type="String" />
          <asp:QueryStringParameter Name="Postnummer" QueryStringField="Postnummer" Type="Int32" />
          <asp:Parameter Name="Emne" Type="String" />
          <asp:Parameter Name="OpslagsID" Type="Int32" />
        </UpdateParameters>
      </asp:SqlDataSource>
    </asp:Panel>
</asp:Content>

为了让一切更加清晰,我正在使用我在aspx后面的代码中的完整代码更新帖子。此外,如果它使理解更好,我正在尝试创建一个论坛。

using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace initial.site
{        
    public partial class forum_front : System.Web.UI.Page
    {
        string qbynavn;
        object objbynavn;

        // Makes the SQL connection string
        String CS = ConfigurationManager.ConnectionStrings["FORADB"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {    
            string qpostnr = Request.QueryString["Postnummer"];
            if (qpostnr != null)
            {
                try
                {
                    using (SqlConnection con = new SqlConnection(CS))
                    {
                        // specifies the command to check for zipcode
                        SqlCommand cmd = new SqlCommand("SELECT Bynavn FROM Postnummertabel WHERE Postnr = " + qpostnr, con);
                        // Opens the connection
                        con.Open();

                        objbynavn = cmd.ExecuteScalar();
                        qbynavn = objbynavn.ToString();

                        ForumOverskrift.Text = " Velkommen til " + qbynavn;
                    }
                }
                catch (Exception ex)
                {
                    Response.Write("Der opstod en fejl! " + ex.Message);
                }
            }
            else
            {
                ForumOverskrift.Text = " Velkommen!";
            }
         }

        public void AnswerButton_Click(object sender, EventArgs e)
        {
            // Tries to bind the sender to the right button.
            Button originator = sender as Button;

            // Checks if it has been found
            if (originator != null)
            {
                // Goes throug the control hierachy to find the right item.
                var parentItem = originator.Parent as ListViewItem;
                if (parentItem != null
                     && parentItem.ItemType == ListViewItemType.DataItem)
                {
                    // Binds the textbox and button to variables
                    var textBox = parentItem.FindControl("AnswerTextBox") as TextBox;
                    var btn = parentItem.FindControl("AnswerButton") as Button;

                    if (textBox != null)
                    {
                        // Changes the textbox to being visible and changes the buttons text.
                        if (textBox.Visible == false)
                        {
                            textBox.Visible = true;
                            btn.Text = "Fortryd";
                        }
                        // Changes the textbox to invisible and changes the buttons text.
                        else if (textBox.Visible == true)
                        {
                            textBox.Visible = false;
                            btn.Text = "Svar";
                        }
                    }
                }
            }
        }

        // Makes the Skriv Opslag field either visible or invisible
        protected void SkrivOpslag_Click(object sender, EventArgs e)
        {
            if (ListView1.InsertItem.Visible == true)
            {
                // Makes the Skriv Opslag field invisible
                ListView1.InsertItem.Visible = false;

                // Changes the buttons name to Skriv Opslag
                Button btn = (Button) ListView1.FindControl("SkrivOpslag");
                btn.Text = "Skriv Opslag";
            }
            else if (ListView1.InsertItem.Visible == false)
            {
                // Makes the Skriv Opslag field visible
                ListView1.InsertItem.Visible = true;

                // Changes the Buttons name to Skriv Opslag
                Button btn = (Button)ListView1.FindControl("SkrivOpslag");
                btn.Text = "Fortryd";
            }
        }

        protected void TilForsiden_Click(object serder, EventArgs e)
        {
            Response.Redirect("~/welcomepage.aspx");
        }

        protected void ListView1_ItemDeleting(object sender, ListViewDeleteEventArgs e)
        {
           ClientScript.RegisterStartupScript(GetType(), "hwa", "deletealert();", true);

           //e.Cancel = true;

            //Response.Write("<script>deletealert();</script>");
            //ScriptManager.RegisterClientScriptBlock(this, GetType(), "mykey", "deletealert();", true);
        }
    }
}

2 个答案:

答案 0 :(得分:3)

首先,您必须了解您不能将服务器端代码与客户端代码混合,然后再将服务器代码混合在一起,就像您在ItemDeleting事件中一样。只有在完成服务器端代码执行后页面PostBacks才会触发所有客户端代码。

现在,关于你对插件的使用。您是否从swal函数返回了任何内容?

让我们尝试使用您的第一种方法OnClientClick="return confirm('are you sure')"以旧方式执行此操作。将其修改为OnClientClick="return deletealert();"。现在使用return true/false函数中的JavaScript deletealert(专注于CAPITALS中的评论)

... YOUR OTHER CODE IN DELETEALERT
function (isConfirm) {
    if (isConfirm) {
        swal("Deleted!", "Your imaginary file has been deleted.", "success");
        //RETURN TRUE TO EXECUTE SERVER CODE
        return true;
    } else {
        swal("Cancelled", "Your imaginary file is safe :)", "error");
        //RETURN FALSE TO SKIP SERVER CODE
        return false;
    }
});
... YOUR OTHER CODE

<强>更新

SweetAlert的工作与常规alert有所不同。它确实显示了一个模态窗口,但不会阻止用户发起的任何操作,例如提交,链接点击。因此,解决方法是将href链接存储在var中,显示SweetAlert,然后使用eval恢复该链接。

function deletealert(ctl, event) {
    // STORE HREF ATTRIBUTE OF LINK CTL (THIS) BUTTON
    var defaultAction = $(ctl).prop("href");
    // CANCEL DEFAULT LINK BEHAVIOUR
    event.preventDefault();
    swal({
        title: "Are you sure?",
        text: "You will not be able to recover this imaginary   file!",
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Yes, delete it!",
        cancelButtonText: "No, cancel plx!",
        closeOnConfirm: false,
        closeOnCancel: false
    },
    function (isConfirm) {
        if (isConfirm) {
            swal({ title: "Deleted!", text: "Your imaginary file has been deleted.", type: "success", confirmButtonText: "OK!", closeOnConfirm: false },
            function () {
                // RESUME THE DEFAULT LINK ACTION
                window.location.href = defaultAction;
                return true;
            });
        } else {
            swal("Cancelled", "Your imaginary file is safe :)", "error");
            return false;
        }
    });
}

我已将asp:Button替换为asp:LinkButton,只是为了便于处理preventDefault,然后重新开始操作。

<asp:LinkButton OnClientClick="return deletealert(this, event);" ID="DeleteButton" runat="server" CommandName="Delete" Text="Slet" CssClass="btn btn-default btn-xs" Visible='<%# (string)Eval("BrugerNavn") == "testuser" ? true : false %>' />

只需要处理一个小故障就是当用户最终点击ConfirmButton显示最终success消息时,同时也会执行默认操作,导致postback在最终success消息和FireFox更新后更新为回发。

答案 1 :(得分:0)

您需要在到达服务器之前提示;所以使用jQuery附加到删除按钮单击:

$("#idofplaceholderwrappingtheitems").find("[id$='DeleteButton']").on("click", function(e) {
   //show confirmation here; 
});

在ItemDeleting中显示javascript过程太迟了。