使用 Twitter Bootstrap 在 ASP.NET MVC 中调用模态对话框的最佳方法是什么? [英] What's the best way to call a modal dialog in ASP.NET MVC using Twitter Bootstrap?

查看:13
本文介绍了使用 Twitter Bootstrap 在 ASP.NET MVC 中调用模态对话框的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

解决方案

这是我的小教程,它演示了 Twitter 的 Bootstrap (2.x) 模态对话框,该对话框适用于 ASP.Net MVC 4 中的表单和部分.

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

从一个空的 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")

到目前为止,我们已经准备好使用 MVC 4 的 Bootstrap,所以让我们将一个简单的模型类 MyViewModel.cs 添加到/Models 文件夹:

使用 System.ComponentModel.DataAnnotations;命名空间 MvcApplication1.Models{公共类 MyViewModel{公共字符串 Foo { 获取;放;}[Required(ErrorMessage = "该栏是绝对必需的")]公共字符串栏 { 获取;放;}}}

在 HomeController 中添加以下几行:

使用 MvcApplication1.Models;//...公共 ActionResult 创建(){返回 PartialView("_Create");}[HttpPost]公共 ActionResult 创建(MyViewModel 模型){如果(模型状态.IsValid){尝试{保存更改(模型);返回 Json(new { success = true });}捕获(例外 e){ModelState.AddModelError("", e.Message);}}//发生了不好的事情返回 PartialView("_Create", 模型);}静态无效 SaveChanges(MyViewModel 模型){//取消注释下一行以显示模态错误//throw new Exception("错误测试");}

在 Views/Home 文件夹中创建新的 Partial View 并将其命名为 _Create.cshtml:

@using MvcApplication1.Models@model 我的视图模型<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h3 id="myModalLabel">创建 Foo Bar</h3>

@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>@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">撤消</button><button class="btn btn-primary" type="submit">保存</button>

}

在 Home/Index.cshtml 中,从模板中删除默认内容并将其替换为以下内容:

@{ViewBag.Title = "首页";}<br/><br/><br/>@Html.ActionLink("创建", "创建", null, null, new { id = "btnCreate", @class = "btn btn-small btn-info" })<div id='dialogDiv' class='modal 隐藏淡入'><div id='dialogContent'></div>

@section 脚本 {@Scripts.Render("~/bundles/jqueryval")<script type="text/javascript">$(函数(){//可选:关闭chache$.ajaxSetup({ cache: false });$('#btnCreate').click(function () {$('#dialogContent').load(this.href, function () {$('#dialogDiv').modal({背景:'静态',键盘:真的}, '展示');bindForm(this);});返回假;});});函数 bindForm(对话框){$('form', dialog).submit(function () {$.ajax({网址:this.action,类型:this.method,数据:$(this).serialize(),成功:功能(结果){如果(结果.成功){$('#dialogDiv').modal('hide');//刷新://location.reload();} 别的 {$('#dialogContent').html(result);绑定表单();}}});返回假;});}}

如果您运行您的应用程序,单击主页上的创建"按钮后将出现一个漂亮的 Bootstrap 模式.

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

我希望我的示例阐明了在 MVC 应用程序中整合 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(
                    "~/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.

这篇关于使用 Twitter Bootstrap 在 ASP.NET MVC 中调用模态对话框的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
C#/.NET最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆