ASP.NET MVC Warning Banner Using Bootstrap And AngularUI Bootstrap

MVC

Table of Contents

Introduction

In this article, I will share how to implement the warning banner and reusable Modal using ASP.NET MVC, jQuery, Web API, Bootstrap, AngularJS and AngularUI Bootstrap. Some people refer to a warning banner as a disclaimer banner, consent screen, splash screen, system acceptable use policy, log-on warning banner, login policy, Logon Banner, Logon Notice, etc... Basically, this is the page/notice that appears/displays when the user first visit or logon into the application. Here is the summary on what the reader can extract from this article.

  • How to create warning banner using jQuery + Bootstrap
  • How to create warning banner using AngularJS + AngularUI Bootstrap
  • How to create a simple Web API
  • How to call Web API from MVC Controller
  • How to include anti-forgery token into the AJAX POST Request
  • How to create reusable Modal using MVC partial view and jQuery + Bootstrap
  • How to create reusable Modal using AngularJS Template + AngularUI Bootstrap
  • How to create an Authorization filter

Figure 1 shows the Solution containing two projects, namely CommonApp and WarningBanner respectively. The CommonApp is a simple WebAPI project responsible for returning the warning banner content.

Figure 1

MVC

Warning Banner View

Listing 1 shows the Bootstrap modal markup in the WarningPage view. In this example, the content for the modal-body will be read from the ViewBag. You can change it to bind from the Model or hard-code the banner content onto the page depending on your requirement. The data-keyboard is set to "false" to prevent the user from closing the warning banner by hitting the ESC key on the keyboard.

Listing 1

  1. @{ Html.RenderPartial("~/Views/Shared/_AntiforgeryToken.cshtml"); }  
  2. div class="modal fade" id="myModal" role="dialog" data-keyboard="false" data-backdrop="static">  
  3.     <div class="modal-dialog">  
  4.     <div class="modal-content">  
  5.     <div class="modal-header">  
  6.     <button type="button" class="close" data-dismiss="modal">×</button>  
  7.             </div>  
  8.         @if (ViewBag.SystemWarningMessage != null)  
  9.         {  
  10.     <div class="modal-body"> @Html.Raw(ViewBag.SystemWarningMessage)</div>  
  11.         }  
  12.     <div class="modal-footer">  
  13.     <button type="button" class="btn btn-default" id="btnAcceptPolicy" data-dismiss="modal">OK</button>  
  14.             </div>  
  15.         </div>  
  16.     </div>  
  17. </div> 

Warning Banner View Action

On page load, the WarningPage action method will check if the user clicked on the OK button on the warning banner page. If yes, redirect the request to Home page else get the warning banner message and display it on the page.

Listing 2

  1. public ActionResult WarningPage()  
  2.     {  
  3.         if (Session["SessionOKClick"] != null)  
  4.         {  
  5.             return RedirectToAction("Index");  
  6.         }  
  7.         SetWarningBanner();  
  8.         return View();  
  9.     } 

Shown in listing 3 is the code to set the warning banner content. In this example, the method is getting the content from the Web API through the HttpClient class. The code is very straight forward, however, we can make a few improvements here. The code can be modified to read the Web API URI from a configuration file and sanitize the JSON result before return it to the client. If Web API is not the preferred choice, then we can modify the code to read the content from the database/entity, configuration file or even hard-coded it. The purpose of the cache-control headers in this method is to prevent the browser back button from serving the content from the cache. For instance, if the user click on the browser back button after accepted the policy, the Warning Banner Modal will re-appear and prompt the user to accept the policy again.

Listing 3

  1. internal void SetWarningBanner()  
  2. {  
  3.     Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  4.     Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));  
  5.     Response.Cache.SetNoStore();  
  6.     //Content can be from the database/Entity, Web Services, hardcode here  
  7.     using (var client = new HttpClient())  
  8.     {  
  9.         client.BaseAddress = new Uri("http://localhost:47503");  
  10.         client.DefaultRequestHeaders.Accept.Clear();  
  11.         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  12.         var response = client.GetAsync("api/warningbanner/1").Result;  
  13.         if (response.IsSuccessStatusCode)  
  14.         {  
  15.             string responseString = response.Content.ReadAsStringAsync().Result;  
  16.             JObject json = JObject.Parse(responseString);  
  17.         //you can update the code to sanitize the json output here  
  18.             ViewBag.SystemWarningMessage = json["Content"].ToString();  
  19.         }  
  20.     }  

Warning Banner Web API

Listing 4 shows the contents of the Warning Banner web API controller. This class contains a WarningBanner object with some sample data in it and a Get method to retrieve the WarningBanner by id. Again, feel free to modify this code to read the data from the database/entity, configuration file and etc.

Listing 4

  1. public class WarningBannerController : ApiController  
  2. {  
  3. //sample data   
  4. IList<WarningBanner> warningBanners = new List<WarningBanner>  
  5.     {  
  6.         new WarningBanner { Id = 1, Content = "<b> *** Warning Banner Content 1 ****</b>",  
  7.             LastUpdatedDate = DateTime.Now},  
  8.         new WarningBanner { Id = 2, Content = "<b> *** Warning Banner Content 2 ****</b>",                 
  9.             LastUpdatedDate= DateTime.Now.AddDays(-30)}  
  10.     };  
  11.     public IHttpActionResult Get(int id)  
  12.     {  
  13.         var banner = warningBanners.FirstOrDefault((p) => p.Id == id);  
  14.         if (banner == null)  
  15.         {  
  16.             return NotFound();  
  17.         }  
  18.         return Ok(banner);  
  19.     }  

Warning Banner View OK button click

Listing 5 shows that the Ajax call will be triggered to post to Home/AcceptPolicy method on Ok button click. In this example, the post will include an anti-forgery token and key value pair data. if the request succeeds, the request will be redirected to the page that is initially being requested.

Listing 5

  1. <script type="text/javascript">  
  2.     $(window).load(function () {  
  3.         $('#myModal').modal('show');  
  4.     });  
  5.     jQuery(document).ready(function () {  
  6.         jQuery("#btnAcceptPolicy").click(function () {  
  7.             jQuery.ajax({  
  8.                 type: "POST",  
  9.                 url: '@Url.Content("~/Home/AcceptPolicy")',  
  10.                 data: { rURL: 'someDummyValue' },  
  11.                 beforeSend: function (xhr) { xhr.setRequestHeader('RequestVerificationToken', $("#antiForgeryToken").val()); },  
  12.                 success: function (data) {  
  13.                     window.location.href = data;  
  14.                 }  
  15.             });  
  16.         });  
  17.     });  
  18. </script> 

Warning Banner OK button Action method

The AcceptPolicy action method is being decorated with HttpPost and AjaxValidateAntiForgeryToken attributes. The main purpose of this method is to tell the client what URL to redirect the request to, after user clicks on the Ok button. Refer to listing 6. You can be creative here also by adding additional logic to log the user response into the database. The method accepts one parameter, rURL, that variable is not being used by the code. The goal is to demonstrate that the AJAX post can pass a parameter to the action method. The purpose of SessionOKClick session variable is to keep track if user clicked on the Ok button. On the other hand, SessionReturnUrl session variable contain the URL of the Initial page request. The URL is being set at AuthorizeAttribute.OnAuthorization method which will be discussed in the next section.

Listing 6

  1. [HttpPost]  
  2. [AjaxValidateAntiForgeryToken]  
  3. public ActionResult AcceptPolicy(string rURL)  
  4. {  
  5.     Session["SessionOKClick"] = "1";  
  6.     string decodedUrl = string.Empty;  
  7.     //return url to redirect after user accepted the policy  
  8.     if (Session["SessionReturnUrl"] != null)  
  9.     {  
  10.         decodedUrl = Server.UrlDecode(Session["SessionReturnUrl"].ToString());  
  11.     }  
  12.     if (Url.IsLocalUrl(decodedUrl))  
  13.     {  
  14.         return Json(decodedUrl);  
  15.     }  
  16.     else  
  17.     {  
  18.         return Json(Url.Action("Index""Home"));  
  19.     }  

RequireAcceptPolicy - Custom Authorization filter attribute

Listing 7 shows the custom authorization filter to check if the request needs to be redirected to the warning banner page before the action methods gets invoked by the authorized users. In this example, the OnAuthorization method contains only the logic to handle the warning banner policy. In reality, your application might have other logic to validate authorized user. We can append/merge the code in Listing 7 into your application authorization filter class. The PageToSkipPolicyNotification and PageToShowPolicyNotification methods allow to specify certain page to skip or show the warning banner page respectively. The OnAuthorization method will redirect the request to Warning page if

  • The action is not from Ok button click (AcceptPolicy) and
  • The user must accept the policy before viewing the requested page and
  • The user has not click on the Ok button (AcceptPolicy) before

Recall earlier, the SessionOKClick session variable is being set at WarningPage AcceptPolicy Action method. The purpose of the SessionReturnUrl session variable is to hold the URL of the request. We can’t expect all the users to enter the web application through the /home page, some might enter from /home/contact page, /home/about page, and etc. Let said the user initially enter the web application from /home/contact page. After the user clicks on the Ok button (AcceptPolicy) on the warning page, the request will be redirected to the /home/contact page. If you want to see the warning banner with AngularJS, in the appSettings element of the web.config, set the WaningBannerAngular value to 1.

Listing 7

  1. public class RequireAcceptPolicy : AuthorizeAttribute, IAuthorizationFilter  
  2. {  
  3.     internal static bool PageToSkipPolicyNotification(HttpContext ctx)  
  4.     {  
  5.         string[] pagesToExclude = { "/home/testwarningpage""/home/warningpage"};  
  6.         string pageToCheck = ctx.Request.Path.ToString().ToLower().TrimEnd('/');  
  7.         return pagesToExclude.Contains(pageToCheck) ? true : false;  
  8.     }  
  9.     internal static bool PageToShowPolicyNotification(HttpContext ctx){ ….}  
  10.     public override void OnAuthorization(AuthorizationContext filterContext)  
  11.     {  
  12.         //Other Authorization logic ….  
  13.             ….  
  14.         //don't prompt if the action is from acceptpolicy, and pages to exclude and SessionOKClick != null (user already accepted policy)  
  15.         if (!filterContext.ActionDescriptor.ActionName.ToLower().Contains("acceptpolicy") && !PageToSkipPolicyNotification(HttpContext.Current) &&  
  16.                             HttpContext.Current.Session["SessionOKClick"] == null)  
  17.         {  
  18.             //track the request url, include the query string  
  19.             HttpContext.Current.Session["SessionReturnUrl"] = filterContext.HttpContext.Request.Url.PathAndQuery;  
  20.             //redirect to policy page  
  21.             if (System.Configuration.ConfigurationManager.AppSettings["WaningBannerAngular"] == "1")  
  22.             {  
  23.                 filterContext.Result = new RedirectResult("~/home/WarningPageNg");  
  24.             }  
  25.             else  
  26.             {  
  27.                 filterContext.Result = new RedirectResult("~/home/WarningPage");  
  28.             }  
  29.         }  
  30.     }  

Filter Config

Listing 8 shows how to add the Custom Authorization filter attribute, RequireAcceptPolicy to the global filter collection.

Listing 8

  1. public class FilterConfig  
  2. {  
  3.     public static void RegisterGlobalFilters(GlobalFilterCollection filters)  
  4.     {  
  5.         filters.Add(new RequireAcceptPolicy());  
  6.     }  

Ajax Validate Anti-Forgery Token

The Anti-Forgery Token code is from Passing Anti-Forgery Token to MVC Actions using Ajax Post . Instead of placing the client related code on every single page, the code is placed into a partial view, _AntiforgeryToken.cshtml. You can place the partial view that requires Anti-Forgery Token into a single page or Layout page. Shown in listing 9 is the contents of _AntiforgeryToken.cshtml. The partial view comprises of two hidden fields with the ID antiForgeryToken and antiForgeryTokenNg respectively. The hidden field hold the Anti-Forgery Token generated by the GetAntiForgeryToken method. The antiForgeryTokenNg hidden field is utilized by AngularJS.

Listing 9

  1. @functions{  
  2.     public string GetAntiForgeryToken()  
  3.     {  
  4.         string cookieToken, formToken;  
  5.         AntiForgery.GetTokens(null, out cookieToken, out formToken);  
  6.         return cookieToken + "," + formToken;  
  7.     }  
  8. }  
  9. <input type="hidden" id="antiForgeryToken" value="@GetAntiForgeryToken()" />  
  10. <input id="antiForgeryTokenNg" data-ng-model="antiForgeryToken" type="hidden"  
  11.     data-ng-init="antiForgeryToken='@GetAntiForgeryToken()'" /> 

Listing 10 shows the jQuery AJAX post passing the Anti-Forgery Token to the Controller Action method. You can see the complete JavaScript from listing 5.

Listing 10

  1. beforeSend: function (xhr) { xhr.setRequestHeader('RequestVerificationToken', $("#antiForgeryToken").val()); } 

Listing 11 briefly shows how the AngularJS passing the Anti-Forgery Token to the Controller Action method. Please download the source code because I might skip something in this section. On page load the Controller will read the token from the hidden field and then store it into an array variables namely items. When the users click on the Accept Policy/OK button, the AngularJS $http service will post to the server including the headers property. In this example the header property contain RequestVerificationToken parameter and the value from $scope.items[0]. The array in this example happens to have only one item that's why the position is 0.

Listing 11

  1. // modal controller  
  2. $scope.items = [$scope.antiForgeryToken];  
  3. // OK click  
  4. $http({  
  5.     method: 'POST',  
  6.     url: '/home/AcceptPolicy',  
  7.     params: Indata,  
  8.     headers: {  
  9.         'RequestVerificationToken': $scope.items[0]  
  10.     }  
  11. … 

Warning Banner View using AngularJS

Listing 12 shows the AngulatJS and AngularUI Bootstrap modal markup in the WarningPageNg view. Like the WarningPage view, the content for the modal-body is from the ViewBag. You can change it to bind from the Model or hard-code the banner content onto the page depending on your requirement. The contents of the modal are encapsulated in the template under the script directive. The OK button click is routed to the ok() function and openModal() function will be call on page load.

Listing 12

  1. <div ng-controller="modalcontroller">  
  2.     <script type="text/ng-template" id="myModal.html">  
  3.     <div class="modal-header"></div>  
  4.     <div class="modal-body">  
  5.         @if (ViewBag.SystemWarningMessage != null)  
  6.         {  
  7.             <div class="modal-body"> @Html.Raw(ViewBag.SystemWarningMessage)</div>  
  8.         }  
  9.     </div>  
  10.     <div class="modal-footer">  
  11.         <button class="btn btn-default" type="button" ng-click="ok()">OK</button>  
  12.     </div>  
  13.     </script>  
  14.     @{ Html.RenderPartial("~/Views/Shared/_AntiforgeryToken.cshtml"); }  
  15.     <span ng-init="openModal()"></span>  
  16. </div>  
  17. @section scripts{  
  18.     <script src="~/ControllersNg/ModalController.js"></script>  

Shown in listing 13 is the contents of ModalController.js file. Initially, the code will create a new module namely TestAngularApp and declare a dependency on the ui.bootstrap module. Then the code will utilize the Config function to inject $httpProvider provider into the module configuration block in the application. The provider will allow the module to add headers of "X-Requested-With" type to the performed calls. This header is necessary to work well with the AjaxValidateAntiForgeryToken attribute and solve the error "required anti-forgery cookie \"__RequestVerificationToken\" is not present." You can see a list of AngularUI Modal open properties and definition here. The OK button click logics are very similar to listing 5. On button click, the page will post to home/AcceptPolicy method with Anti-Forgery token.

Listing 13

  1.     var app = angular.module('TestAngularApp', ['ui.bootstrap']);  
  2. app.config(['$httpProvider'function ($httpProvider) {  
  3.     $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest';  
  4. }]);  
  5. app.controller('modalcontroller'function ($scope, $uibModal) {  
  6.     $scope.animationsEnabled = true;  
  7.     $scope.openModal = function (size) {  
  8.         $scope.items = [$scope.antiForgeryToken];  
  9.         var ModalInstance = $uibModal.open({  
  10.             animation: $scope.animationsEnabled,  
  11.             templateUrl: 'myModal.html',  
  12.             controller: 'InstanceController',  
  13.             backdrop: false,  
  14.             resolve: {  
  15.                 items: function () { return $scope.items; }  
  16.             }  
  17.         });  
  18.     };  
  19. });  
  20. app.controller('InstanceController'function ($scope, $uibModalInstance, $http, $window, items) {  
  21.     $scope.items = items;  
  22.     $scope.ok = function () {       
  23.         var Indata = { rURL: 'dummyTestParam' };  
  24.         $http({  
  25.             method: 'POST',  
  26.             url: '/home/AcceptPolicy',  
  27.             params: Indata,  
  28.             headers: {'RequestVerificationToken': $scope.items[0] }  
  29.         }).then(function successCallback(response) {  
  30.             $scope.status = response.status;  
  31.             $scope.data = response.data;  
  32.             $window.location.href = response.data;  
  33.         }, function errorCallback(response) {  
  34.         });  
  35.         $uibModalInstance.close();  
  36.     };  
  37.     $scope.cancel = function () {  
  38.         //it dismiss the modal   
  39.         $uibModalInstance.dismiss('cancel');  
  40.     };  
  41. }); 

Reusable Modal using jQuery and Bootstrap

Shown in listing 14 is the HTML markup of the _ModalDialog partial view. In this view, there are placeholders for the Modal dialog title and body and several buttons.

Listing 14

  1. <div class="modal fade" id="SharedModalDialog" role="dialog" data-keyboard="false" data-backdrop="static">  
  2.     <div class="modal-dialog">  
  3.         <div class="modal-content">  
  4.             <div class="modal-header">  
  5.                 <button type="button" class="close" data-dismiss="modal">×</button>  
  6.                 <h4 class="modal-title">[Title]</h4>  
  7.             </div>  
  8.             <div class="modal-body">[Body] </div>  
  9.             <div class="modal-footer">  
  10.                 <button type="button" class="btn btn-default"   
  11.                         id="SharedModalDialogBtnOk" data-dismiss="modal">OK</button>  
  12.                 <button type="button" class="btn btn-default"   
  13.                         id="SharedModalDialogBtnCancel" data-dismiss="modal">Cancel</button>  
  14.             <div>  
  15.         </div>  
  16.     </div>  
  17. </div> 

Listing 15 shows the jQuery plugin namely ModalDialog to display the dialog in the _ModalDialog partial view. The plugin accepts five parameters, you can customize it to fit your requirement. The title and body parameters correspond to the dialog title and body content. The OkButtonText and CancelButtonText parameters will determine the label and the visibility of the OK and Cancel buttons respectively. If OkClickRedirect value is specified, the request will be redirected to the specified URL on OK button click.

Listing 15

  1. $(document).ready(function () {  
  2.     (function ($) {  
  3.         // jQuery plugin definition  
  4.         $.fn.ModalDialog = function (params) {  
  5.             // merge default and user parameters  
  6.             params = $.extend({ title: '', body: '', OkButtonText: '', OkClickRedirect: '', CancelButtonText: '' }, params);  
  7.             if (params.title != '') {  
  8.                 $(".modal-title").text(params.title);  
  9.             }  
  10.             if (params.title != '') {  
  11.                 $(".modal-body").html(params.body);  
  12.             }  
  13.             if (params.OkButtonText != '') {  
  14.                 $("#SharedModalDialogBtnOk").text(params.OkButtonText);  
  15.                 $("#SharedModalDialogBtnOk").show();  
  16.             }  
  17.             else {  
  18.                 $("#SharedModalDialogBtnOk").hide();  
  19.             }  
  20.             if (params.CancelButtonText != '') {  
  21.                 $("#SharedModalDialogBtnCancel").text(params.CancelButtonText);  
  22.                 $("#SharedModalDialogBtnCancel").show();  
  23.             }  
  24.             else {  
  25.                 $("#SharedModalDialogBtnCancel").hide();  
  26.             }  
  27.             if (params.OkClickRedirect != '') {  
  28.                 $("#SharedModalDialogBtnOk").click(function () {  
  29.                     window.location.replace(params.OkClickRedirect);  
  30.                 });  
  31.             }  
  32.             $('#SharedModalDialog').modal('show');  
  33.             // allow jQuery chaining  
  34.             return false;  
  35.         };  
  36.     })(jQuery);  
  37. }); 

Listing 16 shows how to utilize the newly created partial view and jQuery plugin to display a modal dialog. The RenderPartial method can be place into the Layout page. This will be very useful if the application needs to display a simple alert message / notification to the client throughout the application. There are three buttons and examples on how to use the plugins in listing 16.

Listing 16

  1. <input type="button" id="btn1" value="Test Bootstrap Modal - OK button/Redirect" />  
  2. <input type="button" id="btn2" value="Test Bootstrap Modal - multiple button" />  
  3. <input type="button" id="btn3" value="Test Bootstrap Modal - no button" />  
  4. @section scripts {  
  5.     @{  
  6.         Html.RenderPartial("~/Views/Shared/_ModalDialog.cshtml");  
  7.     }  
  8.     <script type="text/javascript">  
  9.         $("#btn1").click(function () {  
  10.             $('#SharedModalDialog').ModalDialog({  
  11.                 title: 'Test - modal',  
  12.                 body: '<b>Do you agree with the term?</b>',  
  13.                 OkButtonText: 'Accept',  
  14.                 OkClickRedirect: '/Home/Index/?test=1'  
  15.             });  
  16.         });  
  17.         $("#btn3").click(function () {  
  18.             $('#SharedModalDialog').ModalDialog({  
  19.                 title: 'Test - modal 2 ',  
  20.                 body: 'This is ANOTHER test <b>content 2222 </b> more <br/> contents .....'  
  21.             });  
  22.         });  
  23.         $("#btn2").click(function () {  
  24.             $('#SharedModalDialog').ModalDialog({  
  25.                 title: 'Test Bootstrap Dialog - multiple button',  
  26.                 body: 'Are you sure you want to delete this record?',  
  27.                 CancelButtonText: 'Cancel',  
  28.                 OkButtonText: 'Yes',  
  29.                 OkClickRedirect: '/Home/Index/?test=2'  
  30.             });  
  31.         });  
  32.     </script>  

Listing 17 shows how to display the dialog on page load or without a button click event.

Listing 17

  1. $(document).ready(function () {  
  2.     $('#SharedModalDialog').ModalDialog({  
  3.         title: 'Test - Page Load',  
  4.         body: 'Display on page load !!!!'  
  5.     });  
  6. }); 

Reusable Modal using AngularJS and AngularUI Bootstrap

Shown in listing 18 is the modal dialog template in the _ModalDialogNg.html file. The button visibility is based on the expression in the ngShow attribute, namely showX, showOK and showCancel respectively. The title and buttons label are accessible through the properties in the scope class. AngularJS ng-bind-html directive is being utilized to display the HTML contents securely in the div element. But still, make sure to sanitize the user-input before displaying it.

Listing 18

  1. <div class="modal-header">  
  2.     <button type="button" class="close" ng-show="showX" ng-click="cancel()">×</button>  
  3.     <h3 class="modal-title">{{title}}</h3>  
  4. </div>  
  5. <div class="modal-body">  
  6.     <div data-ng-bind-html="htmlBind"></div>  
  7. </div>  
  8. <div class="modal-footer">  
  9.     <button class="btn btn-default" ng-show="showOK" type="button" ng-click="ok()">{{btnOkText}}</button>  
  10.     <button class="btn btn-default" ng-show="showCancel" type="button" ng-click="cancel()">{{btnCancelText}}</button>  
  11. </div> 

Listing 19 shows the contents of the ModalPartialController.js file. AngularJS $sce (Strict Contextual Escaping) service is being use in the controller to build the trusted version of the HTML values. $uibModal is a service to create modal windows. The purpose of the $window service is to redirect the request to a particular URL on OK button click. The logic to hide or show a button and setting element labels and values are embedded in listing 19.

Listing 19

  1.     var app = angular.module('TestAngularApp', ['ui.bootstrap']);  
  2. app.controller('modalcontroller'function ($scope, $uibModal, $window) {  
  3.     $scope.openModal = function (title, body, okBtnText, okClickRedirect, cancelBtnText) {  
  4.         $scope.items = [title, body, okBtnText, okClickRedirect, cancelBtnText];  
  5.         var ModalInstance = $uibModal.open({  
  6.             animation: true,  
  7.             templateUrl: '/TemplatesNg/_ModalDialogNg.html',  
  8.             controller: 'InstanceController',  
  9.             backdrop: false,  //disables modal closing by click on the background  
  10.             keyboard: true,     //disables modal closing by click on the ESC key  
  11.             resolve: {  
  12.                 items: function () {  
  13.                     return $scope.items;  
  14.                 }  
  15.             }  
  16.         });  
  17.         ModalInstance.result.then(function (btn) {  
  18.             if (btn == "OK") {  
  19.                 $window.location.href = okClickRedirect;  
  20.             }  
  21.         }, function () { });  
  22.     };  
  23. });  
  24. app.controller('InstanceController'function ($scope, $uibModalInstance, $sce, items) {  
  25.     $scope.items = items;  
  26.     $scope.title = $scope.items[0];  
  27.     $scope.body = $scope.items[1];  
  28.     $scope.btnOkText = $scope.items[2];  
  29.     $scope.btnCancelText = $scope.items[4];  
  30.     var returnUrl = $scope.items[3];  
  31.     //allow html  
  32.     $scope.htmlBind = $sce.trustAsHtml($scope.items[1]);  
  33.     //hide or close the X close button on the top, you can write extra logic here to hide or show it  
  34.     $scope.showX = false;  
  35.     $scope.showOK = true;  
  36.     if ($scope.btnOkText == '') {  
  37.         //hide OK button  
  38.         $scope.showOK = false;  
  39.     }  
  40.     //cancel button  
  41.     $scope.showCancel = true;  
  42.     if ($scope.btnCancelText == '') {  
  43.         $scope.showCancel = false;  
  44.     }  
  45.     //OK clicked  
  46.     $scope.ok = function () {  
  47.         if (returnUrl == '') {  
  48.             $uibModalInstance.close('');  
  49.         } else {  
  50.             $uibModalInstance.close('OK');  
  51.         }  
  52.     };  
  53.     $scope.cancel = function () {  
  54.         //it dismiss the modal   
  55.         $uibModalInstance.dismiss();  
  56.     };  
  57. }); 

Listing 20 shows how the application/view call the AngularUI Bootstrap Modal by passing in different parameters. First, include ModalPartialController.js, the AngularJS controllers from listing 19 on to the page. Then create a div element and include the ng-controller directive with controller class, modalcontroller, as its value. Add a button into the div element and on the ng-click event, specify the openModal method defined in the controller (ModalPartialController.js).

Listing 20

  1. <div ng-controller="modalcontroller">  
  2.     <button class="btn btn-default" type="button"  
  3.             ng-click="openModal('AngularUI Model','Click on <b>Ok</b> to Redirect to Contact page.', 'OK', '/home/Contact', 'Close')">  
  4.                 Modal with redirect</button>  
  5. </div>  
  6. <div ng-controller="modalcontroller">  
  7.     <button class="btn btn-default" type="button"  
  8.             ng-click="openModal('@ViewBag.Something','This is the content<b>body 2</b>', '','', 'Close It')">   
  9.                 Modal with close button only</button>  
  10. </div>  
  11. <div ng-controller="modalcontroller">  
  12.     <button class="btn btn-default" type="button"  
  13.             ng-click="openModal('AngularUI Model 2','This is a notification!', '','', 'Ok')">  
  14.         Modal with OK button only  
  15.     </button>  
  16. </div>  
  17. @section scripts{  
  18.     <script src="~/ControllersNg/ModalPartialController.js"></script>  

Listing 21 shows how to display the dialog on page load or without a button click event.

Listing 21

  1. <div ng-controller="modalcontroller"  
  2.          ng-init="openModal('AngularUI Model Onload','Display on page load!', '','', 'Ok')">  
  3. </div> 

Future Plan

Upgrade the code to user Angular 2 and above and MVC 6 core.

Conclusion

I hope someone will find this information useful and make your programming job easier. If you find any bugs or disagree with the contents or want  help to improve this article, please drop me a line and I'll work with you to correct it. I would suggest downloading the demo and explore it in order to grasp the full concept because I might miss some important information in this article. Please send me an email if you want to help improve this article. Please use the following link to report any issues https://github.com/bryiantan/WarningBanner/issues.

Tested on: Internet Explorer 11,10,9.0, Microsoft Edge 38, Firefox 52, Google Chrome 56.0


History

4/5/2017 – Initial version

4/25/2017 - Updated source code to include additional example to display the Modal contents through AJAX POST and GET method. The examples are in the TestModalDialog page.

4/27/2017 - Updated .NET tag to ASP.NET, added reference to Resources section. Please note that the following section are not in the article, please download the source code and explore it. Please ask if you have questions.

  1. Enabling Cross-Origin Requests (CORS) in Global.asax file
  2. Enabling Cross-Origin Requests (CORS) for more than one URL
  3. Include Anti-Forgery token in the Ajax POST method during the Web API call 

Watch this script in action

http://mvc.ysatech.com/

Download

Download Source Code (https://github.com/bryiantan/WarningBanner )

Resources

A Beginner's Tutorial for Understanding Filters and Attributes in ASP.NET MVC
Calling Webapi 2 service from MVC 5 controller
How to implement Modal popup using Angular UI in ASP.NET MVC
ng-bind-html
Passing Anti-Forgery Token to MVC Actions using Ajax Post
Why ASP.NET MVC Request.IsAjaxRequest method returns false for $http calls from angular


Similar Articles