Вот мое небольшое руководство, которое демонстрирует модальное диалоговое окно Twitter Bootstrap (2.x), которое работает с формами и частями в ASP.Net MVC 4.
Чтобы загрузить подобный проект, но нацеленный на MVC 5.1 и Bootstrap 3.1.1, пожалуйста, посетите этот сайт .
Начните с пустого интернет-шаблона MVC 4.
Добавить ссылку на Bootstrap с помощью NuGet
В App_Start / BundleConfig.cs добавьте следующие строки:
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 Views / Shared / _Layout.cshtml
измените строку @ styles.Render так, чтобы она выглядела так:
@Styles.Render("~/Content/css", "~/Content/themes/base/css", "~/Content/bootstrap")
и строка @ Scripts.Render:
@Scripts.Render("~/bundles/jquery", "~/bundles/jqueryui", "~/bundles/bootstrap")
Пока у нас есть Bootstrap, подготовленный для работы с MVC 4, поэтому давайте добавим простой класс модели MyViewModel.cs в папку / Models:
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; }
}
}
В HomeController Добавьте следующие строки:
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");
}
Создайте новый частичный вид в папке Views / Home и назовите его _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>
}
В файле Home / Index.cshtml удалите содержимое по умолчанию из шаблона и замените его следующим:
@{
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>
}
Если вы запустите свое приложение, после нажатия кнопки «Создать» на домашней странице появится красивый модальный Bootstrap.
Попробуйте раскомментировать строку SaveChanges() //throw
в HomeController.cs, чтобы убедиться, что обработанные ошибки вашего контроллера будут правильно отображаться в диалоговом окне.
Я надеюсь, что в моем примере проясняется весь процесс включения Bootstrap и создания модалов в приложении MVC.