Personally I see this as a recurrent requirement in many views of many ASP.Net MVC applications.
That's why I defined a model class and a partial view:
using Resources;
namespace YourNamespace.Models
{
public class SyConfirmationDialogModel
{
public SyConfirmationDialogModel()
{
this.DialogId = "dlgconfirm";
this.DialogTitle = Global.LblTitleConfirm;
this.UrlAttribute = "href";
this.ButtonConfirmText = Global.LblButtonConfirm;
this.ButtonCancelText = Global.LblButtonCancel;
}
public string DialogId { get; set; }
public string DialogTitle { get; set; }
public string DialogMessage { get; set; }
public string JQueryClickSelector { get; set; }
public string UrlAttribute { get; set; }
public string ButtonConfirmText { get; set; }
public string ButtonCancelText { get; set; }
}
}
And my partial view:
@using YourNamespace.Models;
@model SyConfirmationDialogModel
<div id="@Model.DialogId" title="@Model.DialogTitle">
@Model.DialogMessage
</div>
<script type="text/javascript">
$(function() {
$("#@Model.DialogId").dialog({
autoOpen: false,
modal: true
});
$("@Model.JQueryClickSelector").click(function (e) {
e.preventDefault();
var sTargetUrl = $(this).attr("@Model.UrlAttribute");
$("#@Model.DialogId").dialog({
buttons: {
"@Model.ButtonConfirmText": function () {
window.location.href = sTargetUrl;
},
"@Model.ButtonCancelText": function () {
$(this).dialog("close");
}
}
});
$("#@Model.DialogId").dialog("open");
});
});
</script>
And then, every time you need it in a view, you just use @Html.Partial (in did it in section scripts so that JQuery is defined):
@Html.Partial("_ConfirmationDialog", new SyConfirmationDialogModel() { DialogMessage = Global.LblConfirmDelete, JQueryClickSelector ="a[class=SyLinkDelete]"})
The trick is to specify the JQueryClickSelector that will match the elements that need a confirmation dialog. In my case, all anchors with the class SyLinkDelete but it could be an identifier, a different class etc. For me it was a list of:
<a title="Delete" class="SyLinkDelete" href="/UserDefinedList/DeleteEntry?Params">
<img class="SyImageDelete" alt="Delete" src="/Images/DeleteHS.png" border="0">
</a>