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
This really depends on your design, but you should have a template for the modals.
On a single web app for example, you should have a template lying around that you would create a new instance from each time.
Usually on a normal website you would want to store this template inside a js creation function, so that you won't have to send the file to the user each time via http, and they can have it cached.
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.
Thanks @zjerry the solution is great but jQuery validation does not work, in order to fix you need to change the function bindForm as follow:
function bindForm(dialog) {
$.validator.unobtrusive.parse('form');
$('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;
});
}
Notice the first line of the function, because the form is loaded after jQuery validation was initialized.
Many thanks
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>