什么';这是使用Twitter Bootstrap在ASP.NET MVC中调用模式对话框的最佳方式

本文关键字:调用 MVC NET 模式 对话框 方式 最佳 ASP Bootstrap Twitter 什么 | 更新日期: 2023-09-27 18:14:05

我目前正在一个新项目中使用Twitter的Bootstrap工具包,我对在ASP.NET MVC3中使用模式对话框的最佳方式有疑问。

最好的做法是让Partial包含模态的标记,然后使用javascript将其呈现到页面上,还是有更好的方法?

什么';这是使用Twitter Bootstrap在ASP.NET MVC中调用模式对话框的最佳方式

下面是我的小教程,它演示了Twitter的Bootstrap(2.x(模式对话框,该对话框可以在ASP.Net MVC 4中处理表单和部分。

要下载类似的项目,但针对MVC 5.1和Bootstrap 3.1.1,请访问此网站。

从一个空的MVC 4互联网模板开始。

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

在视图/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")

到目前为止,我们已经准备好使用MVC 4的Bootstrap,所以让我们将一个简单的模型类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文件夹中创建新的Partial View,并将其命名为_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>
}

如果你运行你的应用程序,点击主页上的创建按钮后,会出现一个很好的引导模式。

尝试取消对HomeController.cs中SaveChanges() //throw行的注释,以证明控制器处理的错误将正确显示在对话框中。

我希望我的示例能够阐明在MVC应用程序中合并Bootstrap和创建模式的整个过程。

很好的例子,我不得不对MVC 5和Bootstrap 3.3.7进行一些修改,我将目标div标记更改为以下内容,否则我只得到灰色背景,没有模态对话框。希望这能帮助到别人。

<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>

感谢@zjerry,该解决方案很棒,但jQuery验证不起作用,为了修复此问题,您需要更改函数bindForm,如下所示:

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

注意函数的第一行,因为表单是在初始化jQuery验证之后加载的。

非常感谢

这确实取决于您的设计,但您应该有一个模式的模板。

例如,在一个web应用程序上,您应该有一个模板,每次都可以创建一个新实例。

通常在普通网站上,你会想把这个模板存储在js创建函数中,这样你就不必每次都通过http把文件发送给用户,他们也可以缓存它。