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.

22 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Hi.Nice article.can u give me full mvc database application with navigation and crued operations.
    My mailid=munafkhanit@gmail.com

    ReplyDelete
  3. Hey, this day is too much good for me, since this time I am reading this enormous informative article here at my home. Thanks a lot for massive hard work. bootstrap button with icon

    ReplyDelete
  4. Wow, this is fascinating reading. I am glad I found this and got to read it. Great job on this content. I liked it a lot. Thanks for the great and unique info. bootstrap button classes

    ReplyDelete
  5. There are some fascinating points in time in this article however I don know if I see all of them middle to heart. There may be some validity but I will take hold opinion until I look into it further. Good article , thanks and we want extra! Added to FeedBurner as well website designer nyc

    ReplyDelete
  6. I simply desired to thank you so much yet again. I’m not certain what I would’ve handled without the type of advice shared by you directly on this problem. This was an absolute difficult situation in my view, nevertheless being able to see this professional strategy you solved that forced me to cry with happiness. I will be happy for this support and thus believe you know what a powerful job you were carrying out educating the others all through your website. I’m certain you’ve never met all of us. nyc web designer

    ReplyDelete
  7. Some really nice and utilitarian information on this web site , also I believe the style and design holds good features. branding firms san francisco

    ReplyDelete
  8. This website is my inhalation, really fantastic layout and Perfect written content. branding san francisco

    ReplyDelete
  9. This comment has been removed by the author.

    ReplyDelete
  10. I can’t believe focusing long enough to research; much less write this kind of article. You’ve outdone yourself with this material without a doubt. It is one of the greatest contents. irf640 alternative

    ReplyDelete
  11. Excellent .. Amazing .. I’ll bookmark your blog and take the feeds also…I’m happy to find so many useful info here in the post, we need work out more techniques in this regard, thanks for sharing. textbook answers

    ReplyDelete
  12. An fascinating discussion is value comment. I think that it is best to write extra on this matter, it won’t be a taboo topic however generally people are not enough to talk on such topics. To the next. Cheers 먹튀검증

    ReplyDelete
  13. Hi there! Nice stuff, do keep me posted when you post again something like this! 토토사이트

    ReplyDelete
  14. I really appreciate the kind of topics you post here. Thanks for sharing us a great information that is actually helpful. Good day! 대전1인샵

    ReplyDelete

  15. This site seems to inspire me a lot. Thank you so much for organizing and providing this quality information in an easy to understand way. I think that a healthy era of big data can be maintained only when such high-quality information is continuously produced. And I, too, are working hard to organize and provide such high-quality information. It would be nice to come in once and get information.

    Also visit my site:토토사이트

    ReplyDelete
  16. Thanks for the nice blog. It was very useful for me. I'm happy I found this blog. Thank you for sharing with us,I too always learn something new from your post. 먹튀검증

    ReplyDelete
  17. Positive site, where did u come up with the information on this posting?I have read a few of the articles on your website now, and I really like your style. Thanks a million and please keep up the effective work. 먹튀검증

    ReplyDelete
  18. It's too bad to check your article late. I wonder what it would be if we met a little faster. I want to exchange a little more, but please visit my site 꽁머니 and leave a message!!


    ReplyDelete
  19. Your explanation is organized very easy to understand!!! I understood at once. Could you please post about 먹튀검증업체?? Please!!


    ReplyDelete
  20. Many thanks for the article, I have a lot of spray lining knowledge but always learn something new. Keep up the good work and thank you again. 온라인슬롯


    ReplyDelete
  21. Excellent post it is very helpful and knowledgeable content good work keep it up. ทางเข้าเล่น joker

    ReplyDelete