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:
- ASP.NET MVC 5
- HTML
- JavaScript
- Ajax
- Bootstrap
- JQuery
- C# Programming
You can download the complete source code or you can follow step by step discussion below. The sample code is developed in Microsoft Visual Studio 2013 Ultimate.
Let's begin now:
- Create a new MVC web application project and name it "BootstrapModal".
- 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:

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

- Create new controller under "Controller" folder and name it "ModalController.cs".
- Now, open "RouteConfig.cs" file under "App_Start" folder and replace it with following code:
Here, we have simply changed our default controller to "Modal" and action to "Index".- 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 }
- );
- }
- }
- }
- Open "BundleConfig.cs" file under "App_Start" folder and replace it with the following code:
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.- 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;
- }
- }
- }
- Now, under "Views->Shared" folder, open "_Layout.cshtml" file and replace it with the following code:
In the above code snippet, following lines of code at the bottom are important i.e.- <!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 © @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>
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.- <!-- Modal view -->
- @Html.Partial("_ModalMsgPartial")
- @*Scripts*@
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/jqueryval")
- @Scripts.Render("~/bundles/bootstrap")
- <!-- Modal -->
- @Scripts.Render("~/bundles/custom-modal")
- Under "Views, click Shared" folder, create a new file and name it "_ModalMsgPartial.cshtml" and copy-paste below code snippet into it:
Here, we have simply created our Bootstrap Modal standard structure placeholder.- <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">×</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>
- Now, under "Model" folder, create "ModalViewModels.cs" file and copy paste the following code snippet in it:
This is our simple model for "Modal".- using System.ComponentModel.DataAnnotations;
- namespace BootStrapModal.Models
- {
- public class ModalViewModel
- {
- [Required]
- [Display(Name = "Text")]
- public string Text
- {
- get;
- set;
- }
- }
- }
- Now, open the "ModalContoller.cs" file under "Controller" folder and replace it with following code as shown in the following snippet:
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.- //-----------------------------------------------------------------------
- // <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
- }
- }
- Now, Under "Views->Modal" folder, create the "Index.cshtml" page and replace it with the following code:
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:- @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>
- Under "Scripts" folder, create a new script file i.e. "custom-modal.js" and replace it with the following code:
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.- 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();
- }
- }
Now, execute the application and you will be able to see the following:


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:

Sibeesh VenuPosted Mar 25, 2016, 5:42 AM
Nice Share
Debasis SahaPosted Mar 25, 2016, 12:19 AM
Good One..
Saillesh PawarPosted Mar 25, 2016, 12:11 AM
Nice share sir
Muhammad Aqib ShehzadPosted Mar 24, 2016, 3:29 AM
good elaboration. thanks for sharing
Ankur MistryPosted Mar 24, 2016, 2:10 AM
helpful stuff
Asma KhalidPosted Mar 24, 2016, 12:58 AM
Thanks Everyone
Rajeev PunhaniPosted Mar 24, 2016, 12:50 AM
Nice.
Debasis SahaPosted Mar 24, 2016, 12:08 AM
Good One..
Jaipal ReddyPosted Mar 23, 2016, 11:58 PM
Nice One. .
Kumaresh RajalingamPosted Mar 23, 2016, 9:06 PM
Nice one
Vignesh ManiPosted Mar 23, 2016, 5:30 PM
nice