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 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:
- 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:
- 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 changed our default controller to "Modal" and action to "Index".
- Open "BundleConfig.cs" file under "App_Start" folder and replace it with the following code:
- using System.Web;
- using System.Web.Optimization;
- namespace BootStrapModal
- {
- public class BundleConfig
- {
-
- public static void RegisterBundles(BundleCollection bundles)
- {
-
- bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
- "~/Scripts/jquery-{version}.js"));
-
- 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"));
-
-
- bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
- "~/Scripts/modernizr-*"));
- bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
- "~/Scripts/bootstrap.js",
- "~/Scripts/respond.js"));
-
- 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"));
-
-
- 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.
- Now, under "Views->Shared" folder, open "_Layout.cshtml" file and replace it with the 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 © @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.
- Under "Views, click 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">×</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.
- Now, under "Model" folder, create "ModalViewModels.cs" file and copy paste the 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".
- Now, open the "ModalContoller.cs" file under "Controller" folder and replace it with following code as shown in the following snippet:
-
-
-
-
-
-
- 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;
-
-
-
- public class ModalController : Controller
- {
- #region Index view method.
- #region Get: /Modal/Index method.
-
-
-
-
- public ActionResult Index()
- {
- try
- {
- }
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
-
- return this.View();
- }
- #endregion
- #region POST: /Modal/Index
-
-
-
-
-
- [HttpPost]
- [AllowAnonymous]
- [ValidateAntiForgeryToken]
- public ActionResult Index(ModalViewModel model)
- {
- try
- {
-
- if (ModelState.IsValid)
- {
-
- return this.Json(new { EnableSuccess = true, SuccessTitle = "Success", SuccessMsg = model.Text });
- }
- }
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
-
- 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.
- Now, Under "Views->Modal" folder, create the "Index.cshtml" page and replace it with the 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:
- Under "Scripts" folder, create a new script file i.e. "custom-modal.js" and replace it with the following code:
- var onModalSuccess = function(result)
- {
- if (result.EnableError)
- {
-
- $('#ModalTitleId').html("");
- $('#ModalContentId').html("");
-
- $('#ModalTitleId').append(result.ErrorTitle);
- $('#ModalContentId').append(result.ErrorMsg);
-
- $('#ModalMsgBoxId').modal(
- {
- backdrop: 'static',
- keyboard: false
- });
- }
- else if (result.EnableSuccess)
- {
-
- $('#ModalTitleId').html("");
- $('#ModalContentId').html("");
-
- $('#ModalTitleId').append(result.SuccessTitle);
- $('#ModalContentId').append(result.SuccessMsg);
-
- $('#ModalMsgBoxId').modal(
- {
- backdrop: 'static',
- keyboard: false
- });
-
- $('#ModalformId').get(0).reset();
- }
- }
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:
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: