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

时间:2011-11-11 11:55:24

标签: c# jquery asp.net-mvc-3 twitter-bootstrap

我目前在新项目中使用Twitter's Bootstrap toolkit,我对在ASP.NET MVC3中使用模式对话框的最佳方法提出了疑问。

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

4 个答案:

答案 0 :(得分:56)

这是我的小教程,它演示了Twitter的Bootstrap(2.x)模式对话框,它与ASP.Net MVC 4中的表单和部分一起使用。

要下载类似的项目,但要定位MVC 5.1和Bootstrap 3.1.1,请visit this site

从一个空的MVC 4 Internet模板开始。

使用NuGet添加对Bootstrap的引用

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

在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模式。

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

我希望我的示例澄清了在MVC应用程序中整合Bootstrap和创建模态的整个过程。

答案 1 :(得分:2)

很好的例子,我不得不稍微修改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>

答案 2 :(得分:1)

感谢@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验证初始化之后加载了表单。

非常感谢

答案 3 :(得分:0)

这实际上取决于您的设计,但您应该有模板的模板。

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

通常在普通网站上,您可能希望将此模板存储在js创建函数中,这样您就不必每次都通过http将文件发送给用户,并且可以将其缓存。