使用Ajax回调的Bootbox对话框

时间:2016-10-25 01:55:33

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

我在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对象的新窗口。我想抓住它并打开一个模态。这让我很难过。

3 个答案:

答案 0 :(得分: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' });


        });
    });

答案 1 :(得分:0)

首先,在表单中添加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){
            });
    });
}

答案 2 :(得分:-1)

getJSON

建议使用get代替{{1}},任何问题都告诉我。