Header Ads

ASP.NET MVC5: Lightbox Alternative Bootstrap Modal



Today, I shall be demonstrating that how we can integrate Bootstrap Modal into ASP.NET MVC5 application similar to JQuery base lightbox themed alternative.


Following are some prerequisites before you proceed further in this tutorial:

1) Knowledge of ASP.NET MVC5.  
2) Knowledge of HTML.
3) Knowledge of JavaScript.
4) Knowledge of Ajax.
5) Knowledge of Bootstrap.
6) Knowledge of Jquery.  
7) Knowledge of C# Programming.

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

Download Now!

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 require to include "unobtrusive ajax" jquery package. Open "Manage Nuget Packages for Solution" from "Tools->Nuget Package Manager" as shown below:


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


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:


using System;  
 using System.Collections.Generic;  
 using System.Linq;  
 using System.Web;  
 using System.Web.Mvc;  
 using System.Web.Routing;  
 namespace BootStrapModal  
 {  
   public class RouteConfig  
   {  
     public static void RegisterRoutes(RouteCollection routes)  
     {  
       routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
       routes.MapRoute(  
         name: "Default",  
         url: "{controller}/{action}/{id}",  
         defaults: new { controller = "Modal", action = "Index", id = UrlParameter.Optional }  
       );  
     }  
   }  
 }  

Here, we have simply change our default controller to "Modal" and action to "Index".  
6) Open "BundleConfig.cs" file under "App_Start" folder and replace it with following code:


 using System.Web;  
 using System.Web.Optimization;  
 namespace BootStrapModal  
 {  
   public class BundleConfig  
   {  
     // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862  
     public static void RegisterBundles(BundleCollection bundles)  
     {  
       // Jquery  
       bundles.Add(new ScriptBundle("~/bundles/jquery").Include(  
             "~/Scripts/jquery-{version}.js"));  
       // Jquery validator & unobstrusive ajax  
       bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(  
             "~/Scripts/jquery.unobtrusive-ajax.js",  
             "~/Scripts/jquery.unobtrusive-ajax.min.js",  
             "~/Scripts/jquery.validate*",  
             "~/Scripts/jquery.validate.unobtrusive.js",  
             "~/Scripts/jquery.validate.unobtrusive.min.js"));  
       // Use the development version of Modernizr to develop with and learn from. Then, when you're  
       // ready for production, use the build tool at http://modernizr.com to pick only the tests you need.  
       bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(  
             "~/Scripts/modernizr-*"));  
       bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(  
            "~/Scripts/bootstrap.js",  
            "~/Scripts/respond.js"));  
       // Custom.   
       bundles.Add(new ScriptBundle("~/bundles/custom-modal").Include(  
                  "~/Scripts/custom-modal.js"));  
       bundles.Add(new StyleBundle("~/Content/css").Include(  
            "~/Content/bootstrap.css",  
            "~/Content/site.css"));  
       // Set EnableOptimizations to false for debugging. For more information,  
       // visit http://go.microsoft.com/fwlink/?LinkId=301862  
       BundleTable.EnableOptimizations = true;  
     }  
   }  
 }  

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 following code:


<!DOCTYPE html>  
 <html>  
 <head>  
   <meta charset="utf-8" />  
   <meta name="viewport" content="width=device-width, initial-scale=1.0">  
   <title>@ViewBag.Title</title>  
   @Styles.Render("~/Content/css")  
   @Scripts.Render("~/bundles/modernizr")  
   <!-- Font Awesome -->  
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />  
 </head>  
 <body>  
   <div class="navbar navbar-inverse navbar-fixed-top">  
     <div class="container">  
       <div class="navbar-header">  
         <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
           <span class="icon-bar"></span>  
           <span class="icon-bar"></span>  
           <span class="icon-bar"></span>  
         </button>  
       </div>  
     </div>  
   </div>  
   <div class="container body-content">  
     @RenderBody()  
     <hr />  
     <footer>  
       <center>  
         <p><strong>Copyright &copy; @DateTime.Now.Year - <a href="http://asmak9.blogspot.com/">Asma's Blog</a>.</strong> All rights reserved.</p>  
       </center>  
     </footer>  
   </div>  
   <!-- Modal view -->  
   @Html.Partial("_ModalMsgPartial")  
   @*Scripts*@  
   @Scripts.Render("~/bundles/jquery")  
   @Scripts.Render("~/bundles/jqueryval")  
   @Scripts.Render("~/bundles/bootstrap")  
   <!-- Modal -->  
   @Scripts.Render("~/bundles/custom-modal")  
   @RenderSection("scripts", required: false)  
 </body>  
 </html>  

In the above code snippet, following lines of code at the bottom are important i.e.


  <!-- Modal view -->  
   @Html.Partial("_ModalMsgPartial")  
   @*Scripts*@  
   @Scripts.Render("~/bundles/jquery")  
   @Scripts.Render("~/bundles/jqueryval")  
   @Scripts.Render("~/bundles/bootstrap")  
   <!-- Modal -->  
   @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->Shared" folder, create a new file and name it "_ModalMsgPartial.cshtml" and copy-paste below code snippet into it:


 <div id="ModalMsgBoxId"  
    class="modal fade"  
    tabindex="-1"  
    role="dialog">  
   <div class="modal-dialog modal-lg">  
     <div class="modal-content">  
       <div class="modal-header">  
         <button type="button" class="close" data-dismiss="modal" aria-label="Close">  
           <span aria-hidden="true">&times;</span>  
         </button>  
         <h4 class="modal-title">  
           <strong id="ModalTitleId" style="margin-left: 6px; font-size: 16px;"></strong>  
         </h4>  
       </div>  
       <div class="modal-body">  
         <p>  
           <div id="ModalContentId" style="margin-left: 6px; font-size: 16px;"></div>  
         </p>  
       </div>  
       <div class="modal-footer">  
         <button id="normalOkId" type="button" class="btn btn-success" data-dismiss="modal">OK</button>  
       </div>  
     </div>  
   </div>  
 </div>  

Here, we have simply created our Bootstrap Modal standard structure placeholder.  

9) Now, under "Model" folder, create "ModalViewModels.cs" file and copy-paste following code snippet in it:


 using System.ComponentModel.DataAnnotations;  
 namespace BootStrapModal.Models  
 {  
   public class ModalViewModel  
   {  
     [Required]  
     [Display(Name = "Text")]  
     public string Text { get; set; }  
   }  
 }  

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 below snippet:


//-----------------------------------------------------------------------  
 // <copyright file="ModalController.cs" company="None">  
 //   Copyright (c) Allow to distribute this code.  
 // </copyright>  
 // <author>Asma Khalid</author>  
 //-----------------------------------------------------------------------  
 namespace BootStrapModal.Controllers  
 {  
   using System;  
   using System.Collections.Generic;  
   using System.Linq;  
   using System.Security.Claims;  
   using System.Threading.Tasks;  
   using System.Web;  
   using System.Web.Mvc;  
   using BootStrapModal.Models;  
   /// <summary>  
   /// Modal controller class.  
   /// </summary>  
   public class ModalController : Controller  
   {  
     #region Index view method.  
     #region Get: /Modal/Index method.  
     /// <summary>  
     /// Get: /Modal/Index method.  
     /// </summary>      
     /// <returns>Return index view</returns>  
     public ActionResult Index()  
     {  
       try  
       {  
       }  
       catch (Exception ex)  
       {  
         // Info  
         Console.Write(ex);  
       }  
       // Info.  
       return this.View();  
     }  
     #endregion  
     #region POST: /Modal/Index  
     /// <summary>  
     /// POST: /Modal/Index  
     /// </summary>  
     /// <param name="model">Model parameter</param>  
     /// <returns>Return - Modal content</returns>  
     [HttpPost]  
     [AllowAnonymous]  
     [ValidateAntiForgeryToken]  
     public ActionResult Index(ModalViewModel model)  
     {  
       try  
       {  
         // Verification  
         if (ModelState.IsValid)  
         {  
           // Info.  
           return this.Json(new { EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = model.Text });  
         }  
       }  
       catch (Exception ex)  
       {  
         // Info  
         Console.Write(ex);  
       }  
       // Info  
       return this.Json(new { EnableError = true, ErrorTitle = "Error", ErrorMsg = "Something goes wrong, please try again later" });  
     }  
     #endregion  
     #endregion  
   }  
 }  

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 following code:


@using BootStrapModal.Models  
 @model BootStrapModal.Models.ModalViewModel  
 @{  
   ViewBag.Title = "Bootstrap Modal with ASP.NET MVC5 C#";  
 }  
 <div class="row">  
   <div class="panel-heading">  
     <div class="col-md-8 custom-heading3">  
       <h3>  
         <i class="fa fa-file-text-o"></i>  
         <span>Bootstrap Modal with ASP.NET MVC5 C#</span>  
       </h3>  
     </div>  
   </div>  
 </div>  
 <div class="row">  
   <section class="col-md-4 col-md-push-4">  
     @using (Ajax.BeginForm("Index", "Modal", new AjaxOptions { HttpMethod = "POST", OnSuccess = "onModalSuccess" }, new { @id = "ModalformId", @class = "form-horizontal", role = "form" }))  
     {  
       @Html.AntiForgeryToken()  
       <div class="well bs-component">  
         <br />  
         <div class="row">  
           <div class="col-md-12 col-md-push-2">  
             <div class="form-group">  
               <div class="col-md-10 col-md-pull-1">  
                 @Html.TextBoxFor(m => m.Text, new { placeholder = Html.DisplayNameFor(m => m.Text), @class = "form-control" })  
                 @Html.ValidationMessageFor(m => m.Text, "", new { @class = "text-danger custom-danger" })  
               </div>  
             </div>  
             <div class="form-group">  
               <div class="col-md-18">  
               </div>  
             </div>  
             <div class="form-group">  
               <div class="col-md-4 col-md-push-2">  
                 <div >  
                   <button type="submit" class="btn btn-default" value="Process">  
                     <span>Process</span>  
                   </button>  
                 </div>  
               </div>  
             </div>  
           </div>  
         </div>  
       </div>  
     }  
   </section>  
 </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 following code:


var onModalSuccess = function (result)  
 {  
   if (result.EnableError)  
   {  
     // Clear.  
     $('#ModalTitleId').html("");  
     $('#ModalContentId').html("");  
     // Setting.  
     $('#ModalTitleId').append(result.ErrorTitle);  
     $('#ModalContentId').append(result.ErrorMsg);  
     // Show Modal.  
     $('#ModalMsgBoxId').modal(  
       {  
         backdrop: 'static',  
         keyboard: false  
       });  
   }  
   else if (result.EnableSuccess)  
   {  
     // Clear.  
     $('#ModalTitleId').html("");  
     $('#ModalContentId').html("");  
     // Setting.  
     $('#ModalTitleId').append(result.SuccessTitle);  
     $('#ModalContentId').append(result.SuccessMsg);  
     // Show Modal.  
     $('#ModalMsgBoxId').modal(  
       {  
         backdrop: 'static',  
         keyboard: false  
       });  
     // Resetting form.  
     $('#ModalformId').get(0).reset();  
   }  
 }  

In 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 do 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 following:


 

That's about it.

Enjoy!! Coding.