Bootstrap 模式表单在提交后不会关闭 [英] Bootstrap modal form does not close after submit

查看:75
本文介绍了Bootstrap 模式表单在提交后不会关闭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要做的是显示一个弹出窗口来向我的数据库添加一条新记录,我使用的是引导程序 3,我喜欢它,因为我没有使用一行 jquery,而且我的表单非常好(显然它们是基于jquery).

我正在通过 ajax 验证我的表单,但现在的问题是我的模态永远不会关闭,当我尝试重定向到一个动作时,动作会加载到我的模态中,所以我的问题是如何停止我的模态?

这是这段代码的作用的一个例子:

我的表格:

验证时我的表单:

这是完美的代码:

<div class="modal-body">@using (Ajax.BeginForm("ModalAdd", new AjaxOptions() {UpdateTargetId = "mymodalform"})){<div id="mymodalform">@Html.Partial("CreatePartialView", new Car())

}

</div><!--/.modal-content --></div><!--/.modal-dialog -->

和我的部分:

@model ControliBootstrap.Models.Car<div class="form-horizo​​ntal" >@Html.ValidationSummary(true)<div class="form-group">@Html.LabelFor(model => model.Model, new { @class = "control-label col-md-2" })<div class="col-md-10">@Html.EditorFor(model => model.Model)@Html.ValidationMessageFor(model =>model.Model)

<!--更多字段--><div class="form-group"><div class="col-md-offset-2 col-md-10"><input type="submit" value="Create" class="btn btn-default"/>

现在的问题是,当模型在我的控制器中有效时,我转到加载在我的模态中的索引操作,所以我的问题再次是如何关闭我的模态?

这是我的控制器:

public ActionResult ModalAdd(Car car){如果(模型状态.IsValid){db.Cars.Add(car);db.SaveChanges();return RedirectToAction("索引");}return PartialView("CreatePartialView",car);}

解决方案

只是为了记录,我找到了我的答案希望能帮到别人,很难找到完整的文章.

我不得不使用更多的 jquery,但这是一个干净的答案(我认为).

在我的模型中使用数据注释:

[必填]公共字符串名称 { 获取;放;}[必需的]公共字符串电话{得到;放;}

然后我在我的共享文件夹中创建了一个包含我的模态表单的部分,以便我可以将其设为全局.

@model Controli.Models.Provider<!-- 模态--><div class="modalfade" id="mdlnewprovider" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog"><div class="modal-content">@using (Html.BeginForm("Add", "Providers", FormMethod.Post, new { id = "frmnewprovider" })){<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button><h4 class="modal-title" id="myModalLabel">Nuevo Proveedor</h4>

<div class="modal-body"><div class="form-group">@Html.TextBoxFor(u => u.Name, new { @class = "form-control", @placeholder = HttpUtility.HtmlDecode(@Html.DisplayNameFor(u => u.Name).ToHtmlString()) })@Html.ValidationMessageFor(u => u.Name)

<!--更多文本框和验证消息-->

<div class="modal-footer"><input type="submit" value="Agregar" class="btn btn-primary"/>

}</div><!--/.modal-content --></div><!--/.modal-dialog --></div><!--/.modal -->

还有脚本:

var frmnewprovider = $("#forms-providers-new");$(document).ready(function () {frmnewprovider.submit(function (e) {e.preventDefault();frmnewprovider.validate();如果(frmnewprovider.valid()){$.ajax({url: "/Providers/Add",类型:POST",contentType: "application/json; charset=utf-8",数据:JSON.stringify({名称:frmnewprovider.find('#Name').val(),电话:frmnewprovider.find('#Phone').val(),电子邮件:frmnewprovider.find('#Email').val(),国家:frmnewprovider.find('#Country').val(),状态:frmnewprovider.find('#State').val(),地址:frmnewprovider.find('#Address').val()}),成功:功能(结果){//如果记录被添加到数据库,那么...window.location.replace('/Providers/Index');//我们可以重定向//或者干脆关闭我们的模式.//$('#mdlnewprovider').modal('hide');},错误:函数(结果){警报('错误');}});}});});

现在我要做的就是在我需要的地方渲染我的表单,就是添加这些行:

最后 因为我的模型是客户端验证的 我只是将我的模型添加到我的数据库中,并重定向到索引视图,而 ajax 调用隐藏了活动模式 更新: 我建议在 ajax 调用时决定是重定向还是隐藏模式.喜欢评论.

 public ActionResult Add(Provider provider){if (ModelState.IsValid)//也在服务器端验证!{db.Providers.Add(provider);db.SaveChanges();返回 Json(new{success = true});//返回一个虚拟的json,你可以传递什么//你需要的任何参数.如果代码到达//这点.它总是会成功//在我们的ajax调用中}}

确保您的 web.config 包含:

<add key="ClientValidationEnabled" value="true"/><add key="UnobtrusiveJavaScriptEnabled" value="true"/></appSettings>

我也在使用这些脚本:

<script src="~/Scripts/jquery.validate.js"></script><script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

如果有更好的地方,请告诉我.

What I need to do is to show a popup to add a new record to my database, im using bootstrap 3 and I love it because im not using a single line of jquery, and I have really nice form (obvioulsy they are based in jquery).

I am validating my form via ajax, but the problem now is that my modal never closes, when I try to redirect to an Action the action is loaded inside my modal, so my question is how do I stop my modal?

This is an example of what this code does:

My form:

My form when when validated:

this is perfect with this code:

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
    <div class="modal-content">
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title" id="myModalLabel">Add Car</h4>
        </div>
        <div class="modal-body">
            @using (Ajax.BeginForm("ModalAdd", new AjaxOptions() {UpdateTargetId = "mymodalform"}))
            {
                <div id="mymodalform">
                    @Html.Partial("CreatePartialView", new Car())
                </div>
            }
        </div>
    </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

and my partial:

@model ControliBootstrap.Models.Car

    <div class="form-horizontal" >
    @Html.ValidationSummary(true)

    <div class="form-group">
        @Html.LabelFor(model => model.Model, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Model)
            @Html.ValidationMessageFor(model => model.Model)
        </div>
    </div>

    <!--More fields-->

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default"/>
        </div>
    </div>
</div>

the problem now is than when model is valid in my controller I go to Index Action which is loaded inside my modal so my question again is how do I close my modal?

here is my controller:

public ActionResult ModalAdd(Car car)
    {
        if (ModelState.IsValid)
        {
            db.Cars.Add(car);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return PartialView("CreatePartialView",car);
    }

解决方案

Just for the record, I found my answer hope it helps someone else, it is really hard to find a full article of this.

I had to use more of jquery but It is a clean answer (I think).

Using data annotations in my model:

[Required]
public string Name { get; set; }

[Required]
public string Phone { get; set; }

Then I created a partial in my shared folder that contains my modal form, so I can make it global.

@model Controli.Models.Provider

<!-- Modal -->
<div class="modal fade" id="mdlnewprovider" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
        @using (Html.BeginForm("Add", "Providers", FormMethod.Post, new { id = "frmnewprovider" }))
        {
        <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
            <h4 class="modal-title" id="myModalLabel">Nuevo Proveedor</h4>
        </div>
        <div class="modal-body">
            <div class="form-group">
                @Html.TextBoxFor(u => u.Name, new { @class = "form-control", @placeholder = HttpUtility.HtmlDecode(@Html.DisplayNameFor(u => u.Name).ToHtmlString()) })
                @Html.ValidationMessageFor(u => u.Name)
            </div>
            <!--More Textboxes and Validaton Messages-->
        </div>
        <div class="modal-footer">
            <input type="submit" value="Agregar" class="btn btn-primary" />
        </div>
        }
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

And the script:

var frmnewprovider = $("#forms-providers-new");
$(document).ready(function () {
frmnewprovider.submit(function (e) {
    e.preventDefault();
    frmnewprovider.validate();
    if (frmnewprovider.valid()) {
        $.ajax({
            url: "/Providers/Add",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify({
                Name: frmnewprovider.find('#Name').val(),
                Phone: frmnewprovider.find('#Phone').val(),
                Email: frmnewprovider.find('#Email').val(),
                Country: frmnewprovider.find('#Country').val(),
                State: frmnewprovider.find('#State').val(),
                Address: frmnewprovider.find('#Address').val()
            }),
            success: function (result) {
                //if record was added to db, then...
                window.location.replace('/Providers/Index'); //we can redirect
                //or simply close our modal.
                //$('#mdlnewprovider').modal('hide');
            },
            error: function(result) {
                alert('error');
            }
        });
    }
});
});

Now all I have to do to render my form where ever I need it is to add these lines:

<button class="btn btn-primary" data-toggle="modal" data-target="#mdlnewprovider">
    Nuevo
</button>

@Html.Partial("Modals/Providers/FrmNew", new Provider())

@section scripts
{
<script src="~/Scripts/Modals/Providers/NewProvider.js"></script>
<!--Where this script is the one above-->
}

Finally since my model was client-side validated I just add my model to my database, and redirect to Index view, while the ajax call hides active modal Update: I recommend to decide if redirect or hide modal at ajax call. like commented.

    public ActionResult Add(Provider provider)
    {
        if (ModelState.IsValid) //Validate in server side too!
        {
            db.Providers.Add(provider);
            db.SaveChanges();
            return Json(new{ success = true}); //return a dummy json, you can pass what
                                               //ever parameter you need. if code reach
                                               //this point. it will always hit success 
                                               //in our ajax call
        }
    }

make sure your web.config contains:

<appSettings>
  <add key="ClientValidationEnabled" value="true" />
  <add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>

Im using these scripts too:

<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>

Please let me know if something could be better.

这篇关于Bootstrap 模式表单在提交后不会关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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