I'm currently using Twitter's Bootstrap toolkit on a new project and I had a question on the best way to use the modal dialog in ASP.NET MVC3.
Is the best practice to have a Partial that contains the modal's markup and then use javascript to render that onto the page or is there a better approach?
Step 1 : Start a new ASP.NET MVC Web application. Add a new controller called Home and in the Home controller, the Index method is available to you but there is not a view with it so add a view by right-clicking in Index action. Step 2 : In index. aspx add one HTML button to open our modal popup window like below.
Bootstrap 5 Modal component. Responsive popup window with Bootstrap 5. Examples of with image, modal position i.e. center, z-index usage, modal fade animation, backdrop usage, modal size & more. Modal is a responsive popup used to display extra content.
To trigger the modal window, you need to use a button or a link. Then include the two data-* attributes: data-toggle="modal" opens the modal window. data-target="#myModal" points to the id of the modal.
Here goes my little tutorial which demonstrates Twitter's Bootstrap (2.x) modal dialog that works with forms and partials in ASP.Net MVC 4.
To download similar project but targeting MVC 5.1 and Bootstrap 3.1.1 please visit this site.
Start with an empty MVC 4 Internet template.
Add reference to Bootstrap using NuGet
In the App_Start/BundleConfig.cs add the following lines:
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js")); bundles.Add(new StyleBundle("~/Content/bootstrap").Include( "~/Content/bootstrap.css", "~/Content/bootstrap-responsive.css"));
In the Views/Shared/_Layout.cshtml modify the @styles.Render line so it will look like:
@Styles.Render("~/Content/css", "~/Content/themes/base/css", "~/Content/bootstrap")
and the @Scripts.Render line:
@Scripts.Render("~/bundles/jquery", "~/bundles/jqueryui", "~/bundles/bootstrap")
So far we have Bootstrap prepared to work with MVC 4 so let's add a simple model class MyViewModel.cs to the /Models folder:
using System.ComponentModel.DataAnnotations; namespace MvcApplication1.Models { public class MyViewModel { public string Foo { get; set; } [Required(ErrorMessage = "The bar is absolutely required")] public string Bar { get; set; } } }
In the HomeController Add the following lines:
using MvcApplication1.Models; //... public ActionResult Create() { return PartialView("_Create"); } [HttpPost] public ActionResult Create(MyViewModel model) { if (ModelState.IsValid) { try { SaveChanges(model); return Json(new { success = true }); } catch (Exception e) { ModelState.AddModelError("", e.Message); } } //Something bad happened return PartialView("_Create", model); } static void SaveChanges(MyViewModel model) { // Uncommment next line to demonstrate errors in modal //throw new Exception("Error test"); }
Create new Partial View in the Views/Home folder and name it _Create.cshtml:
@using MvcApplication1.Models @model MyViewModel <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">Create Foo Bar</h3> </div> @using (Html.BeginForm("Create", "Home", FormMethod.Post, new { @class = "modal-form" })) { @Html.ValidationSummary() <div class="modal-body"> <div> @Html.LabelFor(x => x.Foo) @Html.EditorFor(x => x.Foo) @Html.ValidationMessageFor(x => x.Foo) </div> <div> @Html.LabelFor(x => x.Bar) @Html.EditorFor(x => x.Bar) @Html.ValidationMessageFor(x => x.Bar) </div> </div> <div class="modal-footer"> <button class="btn" data-dismiss="modal" aria-hidden="true">Undo</button> <button class="btn btn-primary" type="submit">Save</button> </div> }
In the Home/Index.cshtml remove the default content from the template and replace it with following:
@{ ViewBag.Title = "Home Page"; } <br /> <br /> <br /> @Html.ActionLink("Create", "Create", null, null, new { id = "btnCreate", @class = "btn btn-small btn-info" }) <div id='dialogDiv' class='modal hide fade in'> <div id='dialogContent'></div> </div> @section Scripts { @Scripts.Render("~/bundles/jqueryval") <script type="text/javascript"> $(function () { //Optional: turn the chache off $.ajaxSetup({ cache: false }); $('#btnCreate').click(function () { $('#dialogContent').load(this.href, function () { $('#dialogDiv').modal({ backdrop: 'static', keyboard: true }, 'show'); bindForm(this); }); return false; }); }); function bindForm(dialog) { $('form', dialog).submit(function () { $.ajax({ url: this.action, type: this.method, data: $(this).serialize(), success: function (result) { if (result.success) { $('#dialogDiv').modal('hide'); // Refresh: // location.reload(); } else { $('#dialogContent').html(result); bindForm(); } } }); return false; }); } </script> }
If you run your application, a nice Bootstrap modal will appear after clicking the Create button on the Home page.
Try to uncomment the SaveChanges() //throw
line in HomeController.cs to prove that your controller handled errors will appear correctly in the dialog.
I hope that my sample clarifies a bit whole process of incorporating Bootstrap and creating modals in the MVC application.
Great example, I had to modify slightly for MVC 5 and Bootstrap 3.3.7, I changed the target div tags to the following, otherwise I was just getting the grey background and no modal dialog. Hope this helps someone.
<div id='dialogDiv' class='modal fade' tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div id='dialogContent'></div> </div> </div> </div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With