strickland strickland - 1 month ago 10
C# Question

What's the best way to call a modal dialog in ASP.NET MVC using Twitter Bootstrap?

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?


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(

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");

    public ActionResult Create(MyViewModel model)
        if (ModelState.IsValid)
                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>

@using (Html.BeginForm("Create", "Home", FormMethod.Post, new { @class = "modal-form" }))

<div  class="modal-body">
        @Html.LabelFor(x => x.Foo)
        @Html.EditorFor(x => x.Foo)
        @Html.ValidationMessageFor(x => x.Foo)
        @Html.LabelFor(x => x.Bar)
        @Html.EditorFor(x => x.Bar)
        @Html.ValidationMessageFor(x => x.Bar)

<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Undo</button>
    <button class="btn btn-primary" type="submit">Save</button>


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>

@section Scripts {

<script type="text/javascript">
    $(function () {

        //Optional: turn the chache off
        $.ajaxSetup({ cache: false });

        $('#btnCreate').click(function () {
            $('#dialogContent').load(this.href, function () {
                    backdrop: 'static',
                    keyboard: true
                }, 'show');
            return false;

    function bindForm(dialog) {
        $('form', dialog).submit(function () {
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.success) {
                        // Refresh:
                        // location.reload();
                    } else {
            return false;


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.