【问题标题】:Bootbox Dialog with Ajax Callback带有 Ajax 回调的 Bootbox 对话框
【发布时间】:2017-03-06 22:12:21
【问题描述】:

我在 UI 上有这个按钮,客户将在其中打开一个模式。该模态将加载由 Ajax 检索到的局部视图。

 $('#btnfeedback').on('click', function(e) {
        e.preventDefault();
        var debateModal;


        $.get('@Url.Action("LoadFeedbackModal", "Home")', function() {

        }).done(function(info) {

            debateModal = bootbox.dialog(
                {
                    message: info,
                    title: '<span class="fa fa-wechat"></span> Leave Feedback',
                    closeButton: true
                });
            debateModal.find('.modal-header').removeClass('modal-header').addClass('modal-header-info');


        }).fail(function() {
            debateModal = bootbox.alert({ message: "Problem try later", size: 'small' });


        });
    });

这是我的控制器:

[HttpGet]
public ActionResult LoadFeedbackModal()
{
    return PartialView("Partials/_FeedbackModal", new FeedbackVm());
}

[HttpPost]
public ActionResult LoadFeedbackModal(FeedbackVm feedback)
{
    try
    {
        var fb = Mapper.Map<Feedback>(feedback);

        Db.Feedbacks.Add(fb);

        Db.SaveChanges();

        return Json(new { Mensaje = "Thanks for your feedback", Status = true }, JsonRequestBehavior.AllowGet);
    }
    catch (Exception exception)
    {
        return Json(new { Mensaje = "HUbo un problema :( Intenta luego", Status = false }, JsonRequestBehavior.AllowGet);
    }
}

这是我的部分观点:

    @model TuGrietaLive.ViewModels.Admin.Index.FeedbackVm

@using (Html.BeginForm("LoadFeedbackModal", "Home", FormMethod.Post))

{
    @Html.AntiForgeryToken()

<div class="form-horizontal">
    <p>
        Muchas gracias por tu Feedback. Para nosotros es muy importante.
        <small>Si nos dejas tu correo te podemos contestar :)</small></p>
    <div class="form-group">
        @Html.LabelFor(m => m.FeedbackType, new { @class = "control-label col-md-2 col-xs-12" })
        <div class="col-md-10 col-xs-12">
            @Html.EnumDropDownListFor(model => model.FeedbackType, "Selecciona una Categoria", new { @class = "form-control", name = "FeedbackType" })
            @Html.ValidationMessageFor(model => model.FeedbackType)
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2 col-xs-12">Email <small>(Opcional)</small></label>
        <div class="col-md-10 col-xs-12">
            @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control"} })
            @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Comment, new { @class = "control-label col-md-2 col-xs-12" })
        <div class="col-xs-12 col-md-10 ">
            @Html.EditorFor(model => model.Comment, new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.Comment, "", new { @class = "text-danger", rows = 10 })
        </div>
    </div>

    <button type="submit" id="btnsendFeedback" autofocus class="btn btn-block btn-success">
        <span class="glyphicon glyphicon-envelope"></span>Enviar
    </button>
</div>

}

我可以成功获取视图并且模态绘制部分。现在我想在提交表单后得到服务器的响应。

如何获得发布操作消息?此代码打开一个带有 JSON 对象的新窗口。我想捕捉它并打开一个模式。这可要了我的命。

【问题讨论】:

  • 我假设“表单”是指最后一个代码块中显示的表单?

标签: javascript jquery ajax asp.net-mvc bootbox


【解决方案1】:

您应该在反馈对话框中将按钮类型 btnsendFeedback 更改为 button 而不是 submit

<button type="button" id="btnsendFeedback" autofocus class="btn btn-block btn-success">
    <span class="glyphicon glyphicon-envelope"></span>Enviar
</button>

并在接收到对话框内容时处理btnsendFeedback的点击事件:

    $('#btnfeedback').on('click', function (e) {
        e.preventDefault();
        var debateModal;


        $.ajax({
            url: '@Url.Action("LoadFeedbackModal", "Home")',
            type: 'GET'
        }).done(function (info) {

            debateModal = bootbox.dialog(
                {
                    message: info,
                    title: '<span class="fa fa-wechat"></span> Leave Feedback',
                    closeButton: true
                });
            debateModal.find('.modal-header').removeClass('modal-header').addClass('modal-header-info');

            $('#btnsendFeedback').on('click', function (e) {
                $.ajax({
                    url: '@Url.Action("LoadFeedbackModal")',
                    type: 'POST',
                    dataType: 'json'
                }).done(function (result) {
                    console.log(result.Mensaje);
                });
            });
        }).fail(function (xhr, status, error) {
            debateModal = bootbox.alert({ message: "Problem try later", size: 'small' });


        });
    });

【讨论】:

  • Bob Dust 请查看我的更新。我可以使用 Ajax 获得部分视图,我想要的是在提交表单后捕获服务器响应,因此我不会离开该视图。
【解决方案2】:

首先,向您的表单添加一个 ID 或类,以便我们可以挂钩它的提交事件:

@using (Html.BeginForm("LoadFeedbackModal", "Home", FormMethod.Post, new { @id="feedback-form" }))

然后您可以使用该选择器来获取表单:

var form = $('#feedback-form');

或者,您可以使用find() 从模式中获取表单:

var form = debateModal.find('form');

接下来,为表单的提交事件添加一个事件处理程序:

form.on('submit', function(e){

});

您需要取消本机事件,然后使用serialize() 准备您的 AJAX 数据:

form.on('submit', function(e){
    e.preventDefault();

    var data = form.serialize();
});

完成后,您可以使用$.post 提交表单数据,并按照您认为合适的方式处理:

form.on('submit', function(e){
    e.preventDefault();

    var url = form.attr('action');
    var data = form.serialize();

    $.post(url, data)
        .done(function(response, status, jqxhr){
        })
        .fail(function(jqxhr, status, error){
        });
});

最后,将所有这些放在shown.bs.modal 事件中,以便在对话框可见时连接起来:

debateModal.on('shown.bs.modal', function(){

    var form = debateModal.find('form');
    form.on('submit', function(e){
        // prevent/cancel the native submit
        e.preventDefault();

        var url = form.attr('action'); // or use @Url.Action(), if you prefer
        var data = form.serialize();

        $.post(url, data)
            .done(function(response, status, jqxhr){

                /* Do what you need to with the response, and then close the modal */

                debateModal.modal('hide');
            })
            .fail(function(jqxhr, status, error){
            });
    });
}

【讨论】:

    【解决方案3】:
    $.getJSON('@Url.Action("LoadFeedbackModal", "Home")').done(function(info) {
    
                debateModal = bootbox.dialog(
                    {
                        message: info,
                        title: '<span class="fa fa-wechat"></span> Leave Feedback',
                        closeButton: true
                    });
                debateModal.find('.modal-header').removeClass('modal-header').addClass('modal-header-info');
    
    
            }).fail(function() {
                debateModal = bootbox.alert({ message: "Problem try later", size: 'small' });
           });
    

    建议使用getJSON 而不是get,有任何问题请告诉我。

    【讨论】:

    • 请看我的更新。我可以使用 Ajax 获得部分视图,我想要的是在提交表单后捕获服务器响应,因此我不会离开该视图。
    猜你喜欢
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    相关资源
    最近更新 更多