ASP.NET MVC 5: Lightbox Alternative Bootstrap Modal

Today, I shall be demonstrating how we can integrate Bootstrap Modal into ASP.NET MVC 5 application similar to JQuery base lightbox themed alternative.
 
The following are some prerequisites before you proceed any further in this article:

Prerequisites:

The prerequisites include knowledge about the following technologies: 
  1. ASP.NET MVC 5
  2. HTML
  3. JavaScript
  4. Ajax
  5. Bootstrap
  6. JQuery
  7. C# Programming

You can download the complete source code for this tutorial from here or you can follow step by step discussion below. The sample code is developed in Microsoft Visual Studio 2013 Ultimate.

Let's begin now:

  1. Create a new MVC web application project and name it "BootstrapModal".

  2. I will be using "Ajax.BeginForm(...)" method of ASP.NET MVC5 platform, so, we need to include "unobtrusive ajax" jquery package. Open "Manage Nuget Packages for Solution" from "Tools->Nuget Package Manager" as shown below:

    Nuget Package Manager

  3. Now, choose "Microsoft JQuery Unobtrusive Ajax" package and click "Install" as shown below:

    Microsoft JQuery Unobtrusive Ajax

  4. Create new controller under "Controller" folder and name it "ModalController.cs".

  5. Now, open "RouteConfig.cs" file under "App_Start" folder and replace it with following code:
    1. using System;    
    2. using System.Collections.Generic;    
    3. using System.Linq;    
    4. using System.Web;    
    5. using System.Web.Mvc;    
    6. using System.Web.Routing;    
    7. namespace BootStrapModal    
    8. {    
    9.   public class RouteConfig    
    10.   {    
    11.     public static void RegisterRoutes(RouteCollection routes)    
    12.     {    
    13.       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");    
    14.       routes.MapRoute(    
    15.         name: "Default",    
    16.         url: "{controller}/{action}/{id}",    
    17.         defaults: new { controller = "Modal", action = "Index", id = UrlParameter.Optional }    
    18.       );    
    19.     }    
    20.   }    
    21. }    
    Here, we have simply changed our default controller to "Modal" and action to "Index".

  6. Open "BundleConfig.cs" file under "App_Start" folder and replace it with the following code:
    1. using System.Web;    
    2. using System.Web.Optimization;    
    3. namespace BootStrapModal    
    4. {    
    5.   public class BundleConfig    
    6.   {    
    7.     // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862    
    8.     public static void RegisterBundles(BundleCollection bundles)    
    9.     {    
    10.       // Jquery    
    11.       bundles.Add(new ScriptBundle("~/bundles/jquery").Include(    
    12.             "~/Scripts/jquery-{version}.js"));    
    13.       // Jquery validator & unobstrusive ajax    
    14.       bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(    
    15.             "~/Scripts/jquery.unobtrusive-ajax.js",    
    16.             "~/Scripts/jquery.unobtrusive-ajax.min.js",    
    17.             "~/Scripts/jquery.validate*",    
    18.             "~/Scripts/jquery.validate.unobtrusive.js",    
    19.             "~/Scripts/jquery.validate.unobtrusive.min.js"));    
    20.       // Use the development version of Modernizr to develop with and learn from. Then, when you're    
    21.       // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.    
    22.       bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(    
    23.             "~/Scripts/modernizr-*"));    
    24.       bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(    
    25.            "~/Scripts/bootstrap.js",    
    26.            "~/Scripts/respond.js"));    
    27.       // Custom.     
    28.       bundles.Add(new ScriptBundle("~/bundles/custom-modal").Include(    
    29.                  "~/Scripts/custom-modal.js"));    
    30.       bundles.Add(new StyleBundle("~/Content/css").Include(    
    31.            "~/Content/bootstrap.css",    
    32.            "~/Content/site.css"));    
    33.       // Set EnableOptimizations to false for debugging. For more information,    
    34.       // visit http://go.microsoft.com/fwlink/?LinkId=301862    
    35.       BundleTable.EnableOptimizations = true;    
    36.     }    
    37.   }    
    38. }    
    Here, we have simply added links to our JavaScripts i.e. a new package that we have just installed and a link to our custom made script for Bootstrap Modal that we will be creating in a while.

  7. Now, under "Views->Shared" folder, open "_Layout.cshtml" file and replace it with the following code:
    1. <!DOCTYPE html>  
    2. <html>  
    3.     <head>  
    4.         <meta charset="utf-8" />  
    5.         <meta name="viewport" content="width=device-width, initial-scale=1.0">  
    6.             <title>@ViewBag.Title</title>  
    7.                 @Styles.Render("~/Content/css")   
    8.                 @Scripts.Render("~/bundles/modernizr")   
    9.   
    10.             <!-- Font Awesome -->  
    11.             <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />  
    12.         </head>  
    13.         <body>  
    14.             <div class="navbar navbar-inverse navbar-fixed-top">  
    15.                 <div class="container">  
    16.                     <div class="navbar-header">  
    17.                         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
    18.                             <span class="icon-bar"></span>  
    19.                             <span class="icon-bar"></span>  
    20.                             <span class="icon-bar"></span>  
    21.                         </button>  
    22.                     </div>  
    23.                 </div>  
    24.             </div>  
    25.             <div class="container body-content">  
    26.                 @RenderBody()   
    27.   
    28.                 <hr />  
    29.                 <footer>  
    30.                     <center>  
    31.                         <p>  
    32.                             <strong>Copyright © @DateTime.Now.Year -   
    33.                                 <a href="http://asmak9.blogspot.com/">Asma's Blog</a>.  
    34.                             </strong> All rights reserved.  
    35.                         </p>  
    36.                     </center>  
    37.                 </footer>  
    38.             </div>  
    39.             <!-- Modal view -->  
    40.                 @Html.Partial("_ModalMsgPartial")   
    41.                 @*Scripts*@   
    42.                 @Scripts.Render("~/bundles/jquery")   
    43.                 @Scripts.Render("~/bundles/jqueryval")   
    44.                 @Scripts.Render("~/bundles/bootstrap")   
    45.   
    46.             <!-- Modal -->  
    47.                 @Scripts.Render("~/bundles/custom-modal")   
    48.                 @RenderSection("scripts", required: false)   
    49.   
    50.         </body>  
    51.     </html>  
    In the above code snippet, following lines of code at the bottom are important i.e.
    1. <!-- Modal view -->  
    2. @Html.Partial("_ModalMsgPartial")   
    3. @*Scripts*@   
    4. @Scripts.Render("~/bundles/jquery")   
    5. @Scripts.Render("~/bundles/jqueryval")   
    6. @Scripts.Render("~/bundles/bootstrap")   
    7. <!-- Modal -->  
    8. @Scripts.Render("~/bundles/custom-modal")   
    Here, we include our javascripts and a partial page reference to our Bootstrap Modal. Now, for any lightbox themed plugin to work with, the main requirement is that its base placeholder should exist on the main of the page. So, in ASP.NET MVC5 the main of the page is "_Layout.cshtml" file and here we are simply placing our Bootstrap Modal placeholder.

  8. Under "Views, click Shared" folder, create a new file and name it "_ModalMsgPartial.cshtml" and copy-paste below code snippet into it:
    1. <div id="ModalMsgBoxId"   
    2. class="modal fade"   
    3. tabindex="-1"   
    4. role="dialog">  
    5.     <div class="modal-dialog modal-lg">  
    6.         <div class="modal-content">  
    7.             <div class="modal-header">  
    8.                 <button type="button" class="close" data-dismiss="modal" aria-label="Close">  
    9.                     <span aria-hidden="true">×</span>  
    10.                 </button>  
    11.                 <h4 class="modal-title">  
    12.                     <strong id="ModalTitleId" style="margin-left: 6px; font-size: 16px;"></strong>  
    13.                 </h4>  
    14.             </div>  
    15.             <div class="modal-body">  
    16.                 <p>  
    17.                     <div id="ModalContentId" style="margin-left: 6px; font-size: 16px;"></div>  
    18.                 </p>  
    19.             </div>  
    20.             <div class="modal-footer">  
    21.                 <button id="normalOkId" type="button" class="btn btn-success" data-dismiss="modal">OK</button>  
    22.             </div>  
    23.         </div>  
    24.     </div>  
    25. </div>  
    Here, we have simply created our Bootstrap Modal standard structure placeholder.

  9. Now, under "Model" folder, create "ModalViewModels.cs" file and copy paste the following code snippet in it:
    1. using System.ComponentModel.DataAnnotations;  
    2. namespace BootStrapModal.Models  
    3. {  
    4.     public class ModalViewModel  
    5.     {  
    6.         [Required]  
    7.         [Display(Name = "Text")]  
    8.         public string Text  
    9.         {  
    10.             get;  
    11.             set;  
    12.         }  
    13.     }  
    14. }  
    This is our simple model for "Modal".

  10. Now, open the "ModalContoller.cs" file under "Controller" folder and replace it with following code as shown in the following snippet:
    1. //-----------------------------------------------------------------------    
    2. // <copyright file="ModalController.cs" company="None">  
    3. //   Copyright (c) Allow to distribute this code.    
    4. // </copyright>  
    5. // <author>Asma Khalid</author>  
    6. //-----------------------------------------------------------------------    
    7. namespace BootStrapModal.Controllers    
    8. {    
    9.   using System;    
    10.   using System.Collections.Generic;    
    11.   using System.Linq;    
    12.   using System.Security.Claims;    
    13.   using System.Threading.Tasks;    
    14.   using System.Web;    
    15.   using System.Web.Mvc;    
    16.   using BootStrapModal.Models;    
    17.   /// <summary>  
    18.   /// Modal controller class.    
    19.   /// </summary>  
    20.   public class ModalController : Controller    
    21.   {    
    22.     #region Index view method.    
    23.     #region Get: /Modal/Index method.    
    24.     /// <summary>  
    25.     /// Get: /Modal/Index method.    
    26.     /// </summary>  
    27.     /// <returns>Return index view</returns>  
    28.     public ActionResult Index()    
    29.     {    
    30.       try    
    31.       {    
    32.       }    
    33.       catch (Exception ex)    
    34.       {    
    35.         // Info    
    36.         Console.Write(ex);    
    37.       }    
    38.       // Info.    
    39.       return this.View();    
    40.     }    
    41.     #endregion    
    42.     #region POST: /Modal/Index    
    43.     /// <summary>  
    44.     /// POST: /Modal/Index    
    45.     /// </summary>  
    46.     /// <param name="model">Model parameter</param>  
    47.     /// <returns>Return - Modal content</returns>  
    48.     [HttpPost]    
    49.     [AllowAnonymous]    
    50.     [ValidateAntiForgeryToken]    
    51.     public ActionResult Index(ModalViewModel model)    
    52.     {    
    53.       try    
    54.       {    
    55.         // Verification    
    56.         if (ModelState.IsValid)    
    57.         {    
    58.           // Info.    
    59.           return this.Json(new { EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = model.Text });    
    60.         }    
    61.       }    
    62.       catch (Exception ex)    
    63.       {    
    64.         // Info    
    65.         Console.Write(ex);    
    66.       }    
    67.       // Info    
    68.       return this.Json(new { EnableError = true, ErrorTitle = "Error", ErrorMsg = "Something goes wrong, please try again later" });    
    69.     }    
    70.     #endregion    
    71.     #endregion    
    72.   }    
    73. }    
    Here, we have created two methods for "Index(..)" i.e. "HttpGet" and "HttpPost". "HttpGet" method simply loads the "Index" page with a textbox field and a button. The button will display the Bootstrap Modal with the text in it which we have typed in the provided textbox field. "HttpPost" method will post our typed message to the Bootstrap Modal.

  11. Now, Under "Views->Modal" folder, create the "Index.cshtml" page and replace it with the following code:

    1. @using BootStrapModal.Models   
    2. @model BootStrapModal.Models.ModalViewModel   
    3. @{   
    4. ViewBag.Title = "Bootstrap Modal with ASP.NET MVC5 C#";   
    5. }   
    6.   
    7. <div class="row">  
    8.     <div class="panel-heading">  
    9.         <div class="col-md-8 custom-heading3">  
    10.             <h3>  
    11.                 <i class="fa fa-file-text-o"></i>  
    12.                 <span>Bootstrap Modal with ASP.NET MVC5 C#</span>  
    13.             </h3>  
    14.         </div>  
    15.     </div>  
    16. </div>  
    17. <div class="row">  
    18.     <section class="col-md-4 col-md-push-4">  
    19. @using (Ajax.BeginForm("Index""Modal"new AjaxOptions { HttpMethod = "POST", OnSuccess = "onModalSuccess" }, new { @id = "ModalformId", @class = "form-horizontal", role = "form" }))   
    20. {   
    21. @Html.AntiForgeryToken()   
    22.   
    23.         <div class="well bs-component">  
    24.             <br />  
    25.             <div class="row">  
    26.                 <div class="col-md-12 col-md-push-2">  
    27.                     <div class="form-group">  
    28.                         <div class="col-md-10 col-md-pull-1">  
    29. @Html.TextBoxFor(m => m.Text, new { placeholder = Html.DisplayNameFor(m => m.Text), @class = "form-control" })   
    30. @Html.ValidationMessageFor(m => m.Text, ""new { @class = "text-danger custom-danger" })   
    31. </div>  
    32.                     </div>  
    33.                     <div class="form-group">  
    34.                         <div class="col-md-18"></div>  
    35.                     </div>  
    36.                     <div class="form-group">  
    37.                         <div class="col-md-4 col-md-push-2">  
    38.                             <div >  
    39.                                 <button type="submit" class="btn btn-default" value="Process">  
    40.                                     <span>Process</span>  
    41.                                 </button>  
    42.                             </div>  
    43.                         </div>  
    44.                     </div>  
    45.                 </div>  
    46.             </div>  
    47.         </div>  
    48. }   
    49.   
    50.     </section>  
    51. </div>  
    In the above code, we have created a simple Ajax base form with an input text box and a button. In above code we have also stated in "Ajax.BeginForm(..)" that upon every successful response from the controller go to "onModalSuccess" JavaScript base method. Let's create this method now:

  12. Under "Scripts" folder, create a new script file i.e. "custom-modal.js" and replace it with the following code:
    1. var onModalSuccess = function(result)  
    2. {  
    3.     if (result.EnableError)  
    4.     {  
    5.         // Clear.   
    6.         $('#ModalTitleId').html("");  
    7.         $('#ModalContentId').html("");  
    8.         // Setting.   
    9.         $('#ModalTitleId').append(result.ErrorTitle);  
    10.         $('#ModalContentId').append(result.ErrorMsg);  
    11.         // Show Modal.   
    12.         $('#ModalMsgBoxId').modal(  
    13.         {  
    14.             backdrop: 'static',  
    15.             keyboard: false  
    16.         });  
    17.     }  
    18.     else if (result.EnableSuccess)  
    19.     {  
    20.         // Clear.   
    21.         $('#ModalTitleId').html("");  
    22.         $('#ModalContentId').html("");  
    23.         // Setting.   
    24.         $('#ModalTitleId').append(result.SuccessTitle);  
    25.         $('#ModalContentId').append(result.SuccessMsg);  
    26.         // Show Modal.   
    27.         $('#ModalMsgBoxId').modal(  
    28.         {  
    29.             backdrop: 'static',  
    30.             keyboard: false  
    31.         });  
    32.         // Resetting form.   
    33.         $('#ModalformId').get(0).reset();  
    34.     }  
    35. }  
    In the above code, we are creating "onModalSuccess" method which will display Bootstrap Modal with both success and error message that is received from the server side with the properties defined by the server side i.e. "EnableSuccess, EnableError, SuccessTitle, SuccessMsg, ErrorTitle, ErrorMsg." In above code we are also constraining our Bootstrap Modal to not allow the user to close the Bootstrap Modal whenever user clicks on the outside black space behind the Bootstrap Modal or whenever user presses "Esc"key from the keyboard. User can only close the Bootstrap Modal by clicking "OK or X" buttons placed on the Bootstrap Modal.

Now, execute the application and you will be able to see the following:

Run

Success

Conclusion

This article is about integrating Bootstrap Modal with ASP.NET MVC 5 application similar to JQuery base lightbox themed alternative. You will learn the basics of Bootstrap Modal in this article and you will also learn about how to use “Ajax.BeginForm” method.

Read more articles on ASP.NET:
 

Up Next
    Ebook Download
    View all
    Learn
    View all