我个人认为这是许多ASP.Net MVC应用程序的许多视图中经常出现的要求。
这就是为什么我定义了模型类和局部视图的原因:
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; }
}
}
我的部分观点是:
@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>
然后,每次在视图中需要它时,只需使用@ Html.Partial(在节脚本中使用了它,以便定义了JQuery):
@Html.Partial("_ConfirmationDialog", new SyConfirmationDialogModel() { DialogMessage = Global.LblConfirmDelete, JQueryClickSelector ="a[class=SyLinkDelete]"})
技巧是指定将与需要确认对话框的元素匹配的JQueryClickSelector。就我而言,所有锚都具有SyLinkDelete类,但它可以是标识符,其他类等。对我而言,它是以下列表:
<a title="Delete" class="SyLinkDelete" href="/UserDefinedList/DeleteEntry?Params">
<img class="SyImageDelete" alt="Delete" src="/Images/DeleteHS.png" border="0">
</a>