使用 Bootstrap 和 AngularUI Bootstrap 实现 ASP.NET MVC 警告横幅






4.97/5 (9投票s)
作者正在分享一篇关于如何使用 ASP.NET MVC、jQuery、Bootstrap、AngularJS 和 AngularUI Bootstrap 创建警告横幅和可重用模态框的文章。
目录
- 引言
- 视图
- 查看操作
- Web API
- 点击“确定”按钮
- “确定”按钮的操作方法
- RequireAcceptPolicy - 自定义授权过滤器属性
- 过滤器配置
- AJAX 验证防伪令牌
- 使用 AngularJS 的视图
- 使用 jQuery 和 Bootstrap 创建可重用模态框
- 使用 AngularJS 和 AngularUI Bootstrap 创建可重用模态框
- 未来计划
- 结论
- 历史
- 观看此脚本的实际演示
- 下载
- 资源
引言
在本文中,作者将分享如何使用 ASP.NET MVC、jQuery、Web API、Bootstrap、AngularJS 和 AngularUI Bootstrap 实现警告横幅和可重用模态框。有些人称警告横幅为免责声明横幅、同意屏幕、闪屏、系统可接受使用策略、登录警告横幅、登录策略、登录横幅、登录通知等……基本上,这是用户首次访问或登录应用程序时出现的/显示的页面/通知。以下是读者可以从本文中提取的摘要。
- 如何使用 jQuery + Bootstrap 创建警告横幅
- 如何使用 AngularJS + AngularUI Bootstrap 创建警告横幅
- 如何创建一个简单的 Web API
- 如何从 MVC 控制器调用 Web API
- 如何在 AJAX POST 请求中包含防伪令牌
- 如何使用 MVC 局部视图和 jQuery + Bootstrap 创建可重用模态框
- 如何使用 AngularJS 模板 + AngularUI Bootstrap 创建可重用模态框
- 如何创建一个授权过滤器
图 1 显示了包含 CommonApp 和 WarningBanner 两个项目的解决方案。CommonApp 是一个简单的 WebAPI 项目,负责返回警告横幅内容。
图 1
警告横幅视图
列表 1 显示了 WarningPage 视图中的 Bootstrap 模态框标记。在此示例中,模态框正文的内容将从 ViewBag 读取。您可以根据需要将其更改为从模型绑定或将横幅内容硬编码到页面上。data-keyboard 设置为“false”,以防止用户通过按键盘上的 ESC 键关闭警告横幅。
列表 1
@{ Html.RenderPartial("~/Views/Shared/_AntiforgeryToken.cshtml"); }
<div class="modal fade" id="myModal" role="dialog" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
@if (ViewBag.SystemWarningMessage != null)
{
<div class="modal-body"> @Html.Raw(ViewBag.SystemWarningMessage)</div>
}
<div class="modal-footer">
<button type="button" class="btn btn-default" id="btnAcceptPolicy" data-dismiss="modal">OK</button>
</div>
</div>
</div>
</div>
警告横幅视图操作
页面加载时,WarningPage 操作方法将检查用户是否点击了警告横幅页面上的“确定”按钮。如果是,则将请求重定向到主页,否则获取警告横幅消息并将其显示在页面上。
列表 2
public ActionResult WarningPage()
{
if (Session["SessionOKClick"] != null)
{
return RedirectToAction("Index");
}
SetWarningBanner();
return View();
}
列表 3 显示了设置警告横幅内容的rible代码。在此示例中,该方法通过 HttpClient 类从 Web API 获取内容。代码非常直接,但我们可以在此处进行一些改进。可以修改代码以从配置文件读取 Web API URI,并在将 JSON 结果返回给客户端之前对其进行清理。如果 Web API 不是首选选择,那么我们可以修改代码以从数据库/实体、配置文件甚至硬编码中读取内容。此方法中缓存控制头部的目的是防止浏览器后退按钮从缓存提供内容。例如,如果用户在接受策略后点击浏览器后退按钮,警告横幅模态框将重新出现并提示用户再次接受策略。
列表 3
internal void SetWarningBanner()
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
//Content can be from the database/Entity, Web Services, hardcode here
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://:47503");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.GetAsync("api/warningbanner/1").Result;
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
JObject json = JObject.Parse(responseString);
//you can update the code to sanitize the json output here
ViewBag.SystemWarningMessage = json["Content"].ToString();
}
}
}
警告横幅 Web API
列表 4 显示了警告横幅 Web API 控制器的内容。此类包含一个 WarningBanner 对象,其中包含一些示例数据,以及一个用于按 id 检索 WarningBanner 的 Get 方法。同样,您可以随意修改此代码以从数据库/实体、配置文件等中读取数据。
列表 4
public class WarningBannerController : ApiController
{
//sample data
IList<WarningBanner> warningBanners = new List<WarningBanner>
{
new WarningBanner { Id = 1, Content = "<b> *** Warning Banner Content 1 ****</b>",
LastUpdatedDate = DateTime.Now},
new WarningBanner { Id = 2, Content = "<b> *** Warning Banner Content 2 ****</b>",
LastUpdatedDate= DateTime.Now.AddDays(-30)}
};
public IHttpActionResult Get(int id)
{
var banner = warningBanners.FirstOrDefault((p) => p.Id == id);
if (banner == null)
{
return NotFound();
}
return Ok(banner);
}
}
警告横幅视图“确定”按钮点击
列表 5 显示了点击“确定”按钮时将触发 Ajax 调用以 POST 到 Home/AcceptPolicy 方法。在此示例中,POST 将包含一个防伪令牌和一个键值对数据。如果请求成功,则请求将被重定向到最初请求的页面。
列表 5
<script type="text/javascript">
$(window).load(function () {
$('#myModal').modal('show');
});
jQuery(document).ready(function () {
jQuery("#btnAcceptPolicy").click(function () {
jQuery.ajax({
type: "POST",
url: '@Url.Content("~/Home/AcceptPolicy")',
data: { rURL: 'someDummyValue' },
beforeSend: function (xhr) { xhr.setRequestHeader('RequestVerificationToken', $("#antiForgeryToken").val()); },
success: function (data) {
window.location.href = data;
}
});
});
});
</script>
警告横幅“确定”按钮操作方法
AcceptPolicy 操作方法被装饰了 HttpPost 和 AjaxValidateAntiForgeryToken 属性。此方法的主要目的是在用户点击“确定”按钮后,告知客户端将请求重定向到哪个 URL。参见列表 6。您也可以在这里发挥创意,添加额外的逻辑将用户的响应记录到数据库。该方法接受一个参数 rURL,该变量未被代码使用。目标是演示 AJAX POST 可以将参数传递给操作方法。 SessionOKClick 会话变量的目的是跟踪用户是否点击了“确定”按钮。另一方面,SessionReturnUrl 会话变量包含初始页面请求的 URL。该 URL 在 AuthorizeAttribute.OnAuthorization 方法中设置,将在下一节中讨论。
列表 6
[HttpPost]
[AjaxValidateAntiForgeryToken]
public ActionResult AcceptPolicy(string rURL)
{
Session["SessionOKClick"] = "1";
string decodedUrl = string.Empty;
//return url to redirect after user accepted the policy
if (Session["SessionReturnUrl"] != null)
{
decodedUrl = Server.UrlDecode(Session["SessionReturnUrl"].ToString());
}
if (Url.IsLocalUrl(decodedUrl))
{
return Json(decodedUrl);
}
else
{
return Json(Url.Action("Index", "Home"));
}
}
RequireAcceptPolicy - 自定义授权过滤器属性
列表 7 显示了自定义授权过滤器,用于在授权用户调用操作方法之前检查请求是否需要重定向到警告横幅页面。在此示例中,OnAuthorization 方法仅包含处理警告横幅策略的逻辑。实际上,您的应用程序可能还有其他逻辑来验证授权用户。我们可以将列表 7 中的代码追加/合并到您的应用程序授权过滤器类中。 PageToSkipPolicyNotification 和 PageToShowPolicyNotification 方法允许指定要跳过策略通知的页面或显示策略通知的页面。如果满足以下条件,OnAuthorization 方法将请求重定向到警告页面:
- 操作不是来自“确定”按钮点击(AcceptPolicy),并且
- 用户在查看请求的页面之前必须接受策略,并且
- 用户尚未在之前点击“确定”按钮(AcceptPolicy)
回想一下,SessionOKClick 会话变量在 WarningPage AcceptPolicy 操作方法中设置。 SessionReturnUrl 会话变量的目的是保存请求的 URL。我们不能期望所有用户都通过 /home 页面进入 Web 应用程序,有些人可能会从 /home/contact 页面、/home/about 页面等进入。假设用户最初从 /home/contact 页面进入 Web 应用程序。在警告页面上点击“确定”按钮(AcceptPolicy)后,请求将被重定向到 /home/contact 页面。如果您想使用 AngularJS 查看警告横幅,请在 web.config 的 appSettings 元素中,将 WaningBannerAngular 值设置为 1。
列表 7
public class RequireAcceptPolicy : AuthorizeAttribute, IAuthorizationFilter
{
internal static bool PageToSkipPolicyNotification(HttpContext ctx)
{
string[] pagesToExclude = { "/home/testwarningpage", "/home/warningpage"};
string pageToCheck = ctx.Request.Path.ToString().ToLower().TrimEnd('/');
return pagesToExclude.Contains(pageToCheck) ? true : false;
}
internal static bool PageToShowPolicyNotification(HttpContext ctx){ ….}
public override void OnAuthorization(AuthorizationContext filterContext)
{
//Other Authorization logic ….
….
//don't prompt if the action is from acceptpolicy, and pages to exclude and SessionOKClick != null (user already accepted policy)
if (!filterContext.ActionDescriptor.ActionName.ToLower().Contains("acceptpolicy") && !PageToSkipPolicyNotification(HttpContext.Current) &&
HttpContext.Current.Session["SessionOKClick"] == null)
{
//track the request url, include the query string
HttpContext.Current.Session["SessionReturnUrl"] = filterContext.HttpContext.Request.Url.PathAndQuery;
//redirect to policy page
if (System.Configuration.ConfigurationManager.AppSettings["WaningBannerAngular"] == "1")
{
filterContext.Result = new RedirectResult("~/home/WarningPageNg");
}
else
{
filterContext.Result = new RedirectResult("~/home/WarningPage");
}
}
}
}
过滤器配置
列表 8 显示了如何将自定义授权过滤器属性 RequireAcceptPolicy 添加到全局过滤器集合中。
列表 8
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new RequireAcceptPolicy());
}
}
AJAX 验证防伪令牌
防伪令牌代码来自 使用 AJAX POST 将防伪令牌传递到 MVC 操作。代码没有放在每个单独的页面上,而是放在一个局部视图 _AntiforgeryToken.cshtml 中。您可以将需要防伪令牌的局部视图放在单个页面或布局页面上。列表 9 显示了 _AntiforgeryToken.cshtml 的内容。局部视图包含两个 ID 为 antiForgeryToken 和 antiForgeryTokenNg 的隐藏字段。隐藏字段保存 GetAntiForgeryToken 方法生成的防伪令牌。antiForgeryTokenNg 隐藏字段由 AngularJS 使用。
列表 9
@functions{
public string GetAntiForgeryToken()
{
string cookieToken, formToken;
AntiForgery.GetTokens(null, out cookieToken, out formToken);
return cookieToken + "," + formToken;
}
}
<input type="hidden" id="antiForgeryToken" value="@GetAntiForgeryToken()" />
<input id="antiForgeryTokenNg" data-ng-model="antiForgeryToken" type="hidden"
data-ng-init="antiForgeryToken='@GetAntiForgeryToken()'" />
列表 10 显示了 jQuery AJAX POST 如何将防伪令牌传递到控制器操作方法。您可以在列表 5 中看到完整的 JavaScript。
列表 10
beforeSend: function (xhr) { xhr.setRequestHeader('RequestVerificationToken', $("#antiForgeryToken").val()); }
列表 11 简要显示了 AngularJS 如何将防伪令牌传递到控制器操作方法。请下载源代码,因为我可能在此部分省略了一些内容。页面加载时,控制器将从隐藏字段读取令牌,然后将其存储在名为 items 的数组变量中。当用户点击“接受策略”/“确定”按钮时,AngularJS $http 服务将使用 headers 属性 POST 到服务器。在此示例中,header 属性包含 RequestVerificationToken 参数和 $scope.items[0] 的值。此示例中的数组恰好只有一个项目,因此位置为 0。
列表 11
// modal controller
$scope.items = [$scope.antiForgeryToken];
// OK click
$http({
method: 'POST',
url: '/home/AcceptPolicy',
params: Indata,
headers: {
'RequestVerificationToken': $scope.items[0]
}
…
使用 AngularJS 的警告横幅视图
列表 12 显示了 AngulatJS 和 AngularUI Bootstrap 在 WarningPageNg 视图中的模态框标记。与 WarningPage 视图一样,模态框正文的内容来自 ViewBag。您可以根据需要将其更改为从模型绑定或将横幅内容硬编码到页面上。模态框的内容封装在模板的 script 指令下。点击“确定”按钮将路由到 ok() 函数,页面加载时将调用 openModal() 函数。
列表 12
<div ng-controller="modalcontroller">
<script type="text/ng-template" id="myModal.html">
<div class="modal-header"></div>
<div class="modal-body">
@if (ViewBag.SystemWarningMessage != null)
{
<div class="modal-body"> @Html.Raw(ViewBag.SystemWarningMessage)</div>
}
</div>
<div class="modal-footer">
<button class="btn btn-default" type="button" ng-click="ok()">OK</button>
</div>
</script>
@{ Html.RenderPartial("~/Views/Shared/_AntiforgeryToken.cshtml"); }
<span ng-init="openModal()"></span>
</div>
@section scripts{
<script src="~/ControllersNg/ModalController.js"></script>
}
列表 13 显示了 ModalController.js 文件的内容。最初,代码将创建一个名为 TestAngularApp 的新模块,并声明对 ui.bootstrap 模块的依赖。然后,代码将使用 Config 函数将 $httpProvider 提供程序注入到应用程序的模块配置块中。该提供程序将允许模块将“X-Requested-With”类型的头部添加到执行的调用中。此头部对于与 AjaxValidateAntiForgeryToken 属性协同工作至关重要,并解决错误“所需的防伪 cookie (__RequestVerificationToken) 不存在。”您可以在 此处查看 AngularUI 模态框打开属性和定义的列表。点击“确定”按钮的逻辑与列表 5 非常相似。点击按钮时,页面将 POST 到 home/AcceptPolicy 方法,并附带防伪令牌。
列表 13
var app = angular.module('TestAngularApp', ['ui.bootstrap']);
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';
}]);
app.controller('modalcontroller', function ($scope, $uibModal) {
$scope.animationsEnabled = true;
$scope.openModal = function (size) {
$scope.items = [$scope.antiForgeryToken];
var ModalInstance = $uibModal.open({
animation: $scope.animationsEnabled,
templateUrl: 'myModal.html',
controller: 'InstanceController',
backdrop: false,
resolve: {
items: function () { return $scope.items; }
}
});
};
});
app.controller('InstanceController', function ($scope, $uibModalInstance, $http, $window, items) {
$scope.items = items;
$scope.ok = function () {
var Indata = { rURL: 'dummyTestParam' };
$http({
method: 'POST',
url: '/home/AcceptPolicy',
params: Indata,
headers: {'RequestVerificationToken': $scope.items[0] }
}).then(function successCallback(response) {
$scope.status = response.status;
$scope.data = response.data;
$window.location.href = response.data;
}, function errorCallback(response) {
});
$uibModalInstance.close();
};
$scope.cancel = function () {
//it dismiss the modal
$uibModalInstance.dismiss('cancel');
};
});
使用 jQuery 和 Bootstrap 创建可重用模态框
列表 13 显示了 _ModalDialog 局部视图的 HTML 标记。在此视图中,为模态框标题和正文以及几个按钮提供了占位符。
列表 14
<div class="modal fade" id="SharedModalDialog" role="dialog" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">[Title]</h4>
</div>
<div class="modal-body">[Body] </div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
id="SharedModalDialogBtnOk" data-dismiss="modal">OK</button>
<button type="button" class="btn btn-default"
id="SharedModalDialogBtnCancel" data-dismiss="modal">Cancel</button>
<div>
</div>
</div>
</div>
列表 15 显示了 jQuery 插件 ModalDialog ,用于在 _ModalDialog 局部视图中显示对话框。该插件接受五个参数,您可以自定义以满足您的需求。title 和 body 参数对应于对话框的标题和正文内容。 OkButtonText 和 CancelButtonText 参数将分别确定“确定”和“取消”按钮的标签和可见性。如果指定了 OkClickRedirect 值,则在点击“确定”按钮时,请求将被重定向到指定的 URL。
列表 15
$(document).ready(function () {
(function ($) {
// jQuery plugin definition
$.fn.ModalDialog = function (params) {
// merge default and user parameters
params = $.extend({ title: '', body: '', OkButtonText: '', OkClickRedirect: '', CancelButtonText: '' }, params);
if (params.title != '') {
$(".modal-title").text(params.title);
}
if (params.title != '') {
$(".modal-body").html(params.body);
}
if (params.OkButtonText != '') {
$("#SharedModalDialogBtnOk").text(params.OkButtonText);
$("#SharedModalDialogBtnOk").show();
}
else {
$("#SharedModalDialogBtnOk").hide();
}
if (params.CancelButtonText != '') {
$("#SharedModalDialogBtnCancel").text(params.CancelButtonText);
$("#SharedModalDialogBtnCancel").show();
}
else {
$("#SharedModalDialogBtnCancel").hide();
}
if (params.OkClickRedirect != '') {
$("#SharedModalDialogBtnOk").click(function () {
window.location.replace(params.OkClickRedirect);
});
}
$('#SharedModalDialog').modal('show');
// allow jQuery chaining
return false;
};
})(jQuery);
});
列表 16 显示了如何利用新创建的局部视图和 jQuery 插件来显示模态对话框。 RenderPartial 方法可以放在布局页面中。如果应用程序需要显示简单的警报消息/通知给整个应用程序的客户端,这将非常有用。列表 16 中有三个按钮和使用插件的示例。
列表 16
<input type="button" id="btn1" value="Test Bootstrap Modal - OK button/Redirect" />
<input type="button" id="btn2" value="Test Bootstrap Modal - multiple button" />
<input type="button" id="btn3" value="Test Bootstrap Modal - no button" />
@section scripts {
@{
Html.RenderPartial("~/Views/Shared/_ModalDialog.cshtml");
}
<script type="text/javascript">
$("#btn1").click(function () {
$('#SharedModalDialog').ModalDialog({
title: 'Test - modal',
body: '<b>Do you agree with the term?</b>',
OkButtonText: 'Accept',
OkClickRedirect: '/Home/Index/?test=1'
});
});
$("#btn3").click(function () {
$('#SharedModalDialog').ModalDialog({
title: 'Test - modal 2 ',
body: 'This is ANOTHER test <b>content 2222 </b> more <br/> contents .....'
});
});
$("#btn2").click(function () {
$('#SharedModalDialog').ModalDialog({
title: 'Test Bootstrap Dialog - multiple button',
body: 'Are you sure you want to delete this record?',
CancelButtonText: 'Cancel',
OkButtonText: 'Yes',
OkClickRedirect: '/Home/Index/?test=2'
});
});
</script>
}
列表 17 显示了如何在页面加载时或不经过按钮点击事件的情况下显示对话框。
列表 17
$(document).ready(function () {
$('#SharedModalDialog').ModalDialog({
title: 'Test - Page Load',
body: 'Display on page load !!!!'
});
});
使用 AngularJS 和 AngularUI Bootstrap 创建可重用模态框
列表 18 显示了 _ModalDialogNg.html 文件中的模态对话框模板。按钮的可见性基于 ngShow 属性中的表达式,即 showX、showOK 和 showCancel。标题和按钮标签可以通过作用域类中的属性访问。 AngularJS ng-bind-html 指令被用于在 div 元素中安全地显示 HTML 内容。但仍然,请确保在显示用户输入之前对其进行清理。
列表 18
<div class="modal-header">
<button type="button" class="close" ng-show="showX" ng-click="cancel()">×</button>
<h3 class="modal-title">{{title}}</h3>
</div>
<div class="modal-body">
<div data-ng-bind-html="htmlBind"></div>
</div>
<div class="modal-footer">
<button class="btn btn-default" ng-show="showOK" type="button" ng-click="ok()">{{btnOkText}}</button>
<button class="btn btn-default" ng-show="showCancel" type="button" ng-click="cancel()">{{btnCancelText}}</button>
</div>
列表 19 显示了 ModalPartialController.js 文件的内容。 AngularJS $sce (严格上下文转义)服务在控制器中用于构建 HTML 值的可信版本。 $uibModal 是一个用于创建模态窗口的服务。 $window 服务用于在点击“确定”按钮时将请求重定向到特定 URL。隐藏或显示按钮以及设置元素标签和值的逻辑嵌入在列表 19 中。
列表 19
var app = angular.module('TestAngularApp', ['ui.bootstrap']);
app.controller('modalcontroller', function ($scope, $uibModal, $window) {
$scope.openModal = function (title, body, okBtnText, okClickRedirect, cancelBtnText) {
$scope.items = [title, body, okBtnText, okClickRedirect, cancelBtnText];
var ModalInstance = $uibModal.open({
animation: true,
templateUrl: '/TemplatesNg/_ModalDialogNg.html',
controller: 'InstanceController',
backdrop: false, //disables modal closing by click on the background
keyboard: true, //disables modal closing by click on the ESC key
resolve: {
items: function () {
return $scope.items;
}
}
});
ModalInstance.result.then(function (btn) {
if (btn == "OK") {
$window.location.href = okClickRedirect;
}
}, function () { });
};
});
app.controller('InstanceController', function ($scope, $uibModalInstance, $sce, items) {
$scope.items = items;
$scope.title = $scope.items[0];
$scope.body = $scope.items[1];
$scope.btnOkText = $scope.items[2];
$scope.btnCancelText = $scope.items[4];
var returnUrl = $scope.items[3];
//allow html
$scope.htmlBind = $sce.trustAsHtml($scope.items[1]);
//hide or close the X close button on the top, you can write extra logic here to hide or show it
$scope.showX = false;
$scope.showOK = true;
if ($scope.btnOkText == '') {
//hide OK button
$scope.showOK = false;
}
//cancel button
$scope.showCancel = true;
if ($scope.btnCancelText == '') {
$scope.showCancel = false;
}
//OK clicked
$scope.ok = function () {
if (returnUrl == '') {
$uibModalInstance.close('');
} else {
$uibModalInstance.close('OK');
}
};
$scope.cancel = function () {
//it dismiss the modal
$uibModalInstance.dismiss();
};
});
列表 20 显示了应用程序/视图如何通过传递不同参数来调用 AngularUI Bootstrap 模态框。首先,将列表 19 中的 ModalPartialController.js、AngularJS 控制器包含到页面上。然后创建一个 div 元素并包含 ng-controller 指令,其值为控制器类 modalcontroller。在 div 元素中添加一个按钮,并在 ng-click 事件中,指定控制器(ModalPartialController.js)中定义的 openModal 方法。
列表 20
<div ng-controller="modalcontroller">
<button class="btn btn-default" type="button"
ng-click="openModal('AngularUI Model','Click on <b>Ok</b> to Redirect to Contact page.', 'OK', '/home/Contact', 'Close')">
Modal with redirect</button>
</div>
<div ng-controller="modalcontroller">
<button class="btn btn-default" type="button"
ng-click="openModal('@ViewBag.Something','This is the content<b>body 2</b>', '','', 'Close It')">
Modal with close button only</button>
</div>
<div ng-controller="modalcontroller">
<button class="btn btn-default" type="button"
ng-click="openModal('AngularUI Model 2','This is a notification!', '','', 'Ok')">
Modal with OK button only
</button>
</div>
@section scripts{
<script src="~/ControllersNg/ModalPartialController.js"></script>
}
列表 21 显示了如何在页面加载时或不经过按钮点击事件的情况下显示对话框。
列表 21
<div ng-controller="modalcontroller"
ng-init="openModal('AngularUI Model Onload','Display on page load!', '','', 'Ok')">
</div>
未来计划
将代码升级到使用 Angular 2 及以上版本和 MVC 6 core。
结论
我希望有人能发现这些信息很有用,并使您的编程工作更轻松。如果您发现任何错误、不同意内容或希望帮助改进本文,请给我留言,我将与您一起纠正。我建议下载演示并进行探索,以充分掌握概念,因为我可能在此文中遗漏了一些重要信息。如果您想帮助改进本文,请给我发送电子邮件。请使用以下链接报告任何问题 https://github.com/bryiantan/WarningBanner/issues。
测试于:Internet Explorer 11,10,9.0, Microsoft Edge 38, Firefox 52, Google Chrome 56.0
历史
2017 年 4 月 5 日 – 初始版本
2017 年 4 月 25 日 - 更新了源代码,包含了通过 AJAX POST 和 GET 方法显示模态框内容的附加示例。示例位于 TestModalDialog 页面。
2017 年 4 月 27 日 - 将 .NET 标签更新为 ASP.NET,添加了对“资源”部分的引用。请注意,以下部分不在本文中,请下载源代码并自行探索。如果您有疑问,请随时提问。
- 在 Global.asax 文件中启用跨域请求 (CORS)
- 为多个 URL 启用跨域请求 (CORS)
- 在 Web API 调用期间,在 Ajax POST 方法中包含防伪令牌