Asp.net

JQuery 對話框和 ASP.NET 中繼器

  • April 20, 2015

我有一個 ASP.NET 中繼器,它顯示帶有刪除連結按鈕的項目列表。

我想設置刪除連結按鈕以顯示一個 JQuery 對話框以進行確認。如果點擊“確定”按鈕,我想做回發。

明顯的問題是轉發器中的每個 LinkBut​​ton 都有自己的 ID,我不想複製對話框的所有 javascript。

建議?

解決方案並不是那麼簡單。您必須有能力在按下 jQuery UI Dialog 的 Ok 按鈕後呼叫原始回調函式。

首先,您需要一個通用的 js 函式來顯示對話框:

function showConfirmRequest(callBackFunction, title, content) 
{
   $("#divConfirm").html(content).dialog({
       autoOpen: true,
       modal: true, 
       title: title,
       draggable: true,
       resizable: false,
       close: function(event, ui) { $(this).dialog("destroy"); },
       buttons: { 
           'Ok': function() { callBackFunction(); },
           'Cancel': function() {
               $(this).dialog("destroy");
           }
       },
       overlay: { 
           opacity: 0.45, 
           background: "black" 
       } 
   });
}

我想像這樣的 div 的存在

<div id="divConfirm"></div>

在 c# 程式碼隱藏中,您必須註冊以前的客戶端函式,將控制項的原始 asp.net callbackFunction 作為參數傳遞(我概括了):

protected void AddConfirmRequest(WebControl control, string title, string message) 
{
   string postBackReference = Page.ClientScript.GetPostBackEventReference(control, String.Empty);
   string function = String.Format("javascript:showConfirmRequest(function() {{ {0} }}, '{1}', '{2}'); return false;", 
                                    postBackReference,
                                    title,
                                    message);
   control.Attributes.Add("onclick", function);
}

通過 GetPostBackEventReference 方法,您可以檢索 asp.net 分配給控制項的回發函式。

現在,在 Repeater ItemDataBound 上,檢索執行刪除的控制項並將其傳遞給此函式:

<asp:Repeater ID="repeater" runat="server" OnItemDataBound="repeater_OnItemDataBound">
   ...
   <ItemTemplate>
       ...
       <asp:Button ID="btnDelete" runat="server" Text="Delete" />
       ...
   </ItemTemplate>
</asp:Repeater>

和程式碼:

protected void repeater_OnItemDataBound(object sender, RepeaterItemEventArgs e)
{
   if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
   {
       WebControl btnDelete = ((WebControl)e.Item.FindControl("btnDelete"));
       AddConfirmRequest(btnDelete, "Confirm delete", "Are you sure? Really???");
   }
}

我希望這有幫助。

引用自:https://stackoverflow.com/questions/1570329