MVC - 将[HttpPost]视图加载到Jquery / Ajax模式窗口中

时间:2013-06-05 22:58:40

标签: asp.net-mvc jquery asp.net-mvc-4

我的代码当前工作的方式是当按下按钮时传递变量并且Jquery取消隐藏模态窗口并进行AJAX调用以获取我的Controller Action的[HttpGet]部分。这会在模态窗口中加载一个表单。模态有一个保存和取消按钮,当按下保存按钮时,表单将使用ajaxSubmit提交。成功保存后,会将某些内容保存到数据库中,然后创建一个url并将其传递回jquery,并使用window.location.href重定向用户。

我想要发生的是当按下保存按钮时,控制器动作的[HttpPost]部分将做出一些逻辑选择,如果在动作中满足某个条件,则返回返回PartialView(模型)返回模态窗口并显示错误消息或弹出,以便用户无需重新键入其信息并了解保存未执行的原因,可以快速编辑并尝试再次保存。

Jquery:

var createNewClaimSetup = function () {

    $(selectors.btnCreateNewClaim).live('click', function () {

        var serialNumber = $(this).attr(attributes.serialNumber);
        var spaRegistrationId = $(this).attr(attributes.spaRegistrationId);
        var customerNumber = $(this).attr(attributes.customerNumber);
        var customerStatementName = $(this).attr(attributes.customerStatementName);

        $(selectors.serialNumberHidden).val(serialNumber);
        $(selectors.spaRegistationIdHidden).val(spaRegistrationId);
        $(selectors.customerNumberHidden).val(customerNumber);
        $(selectors.customerStatementName).val(customerStatementName);

        $(selectors.dialog).attr(attributes.title, 'Create New Claim');

        $.ajax ({
            url: inputs.warrantyClaimCreateUrl,
            type: "GET",
            data: {
                   serialNumber: serialNumber,
                   customerNumber: customerNumber
                },
             cache: false,
             success: function (result) {
                $(selectors.dialog).html(result.toString());
                $(selectors.dialog).dialog ({
                     resizable: false,
                    height: 600,
                    width: 850,
                    modal: true,
                    buttons: {
                        'Save': function () {
                        // check to see if a value has been entered for problem description before submitting form
                        //
                        if(!$('#AddProblemModel_ProblemDesc').val().length==0 && (!$('#ClaimPrefix').val().length==0 || $('#chkManualClaimNum').is(':checked')))
                            $(selectors.createNewClaimForm).ajaxSubmit({
                                cache: false,
                                success: function (data) {
                                      if (data.length == 0) {
                                        location.reload();
                                        $(selectors.dialog).dialog('close');
                                    } else {
                                        $(selectors.dialog).dialog('close');
                                        window.location.href = data.redirectToUrl;
                                    }
                                }
                            });
                            else{
                                return alert('You must select a prefix and enter a description for the problem before saving');
                            }
                        },
                        Cancel: function () {
                            $(this).dialog('close');
                        }
                      }
                    });
                }

             });

        });
}

Controller Action GET(为简洁起见编辑):

public virtual ActionResult WarrantyClaimCreateNew(string serialNumber, string customerNumber, string customerStatementName)
    {
        WarrantyClaimModel model = wcs.CreateNewClaimInfo(serialNumber, customerNumber, false);

        ViewBag.InvalidPrefix = false;
        ViewBag.DupeWaNum = false;
        return View(model);
    }

控制器动作POST(为简洁起见编辑):

[HttpPost]
    public virtual ActionResult WarrantyClaimCreateNew(WarrantyClaimCreateNewModel model)
    {
        if (ModelState.IsValid)
        {

            WaNumberDupeModel WAdupe = new WaNumberDupeModel(model.WarrantyClaimNumber);
            // Rebuild WarrantyClaimModel object to pass back to view
            WarrantyClaimModel model2 = wcs.CreateNewClaimInfo(model.SerialNumber, model.CustomerNumber, false);

            // check if prefix is valid
            if (WAdupe.DupeType == WaDupeType.InvalidPrefix)
            {
                ViewBag.InvalidPrefix = true;
                return PartialView(model2);
                //return Json(new { Url = Url.Action("WarrantyClaimCreateNew", model2) });
            }
            // check if wa number already exists
            if (WAdupe.DupeExists)
            {
                ViewBag.DupeWaNum = true;
                return PartialView(model2);
            }

            // create/save the new claim
            if (wcs.CreateNewWarrantyClaim(model))
            {
                var redirectString = "WarrantyClaimDetail?warrantyClaimNumber=" + model.WarrantyClaimNumber;

                if (Request.IsAjaxRequest())
                {
                    return Json(new { redirectToUrl = redirectString }, JsonRequestBehavior.AllowGet);
                }

                return RedirectToAction(Actions.WarrantyClaimDetail(newClaimNumber));
            }

            return RedirectToAction(Actions.WarrantyClaimSaveFail());
        }
        else
        {
            return View(model);
        }
    }

视图中的警报如果控制器操作中的条件符合:

<%if (ViewBag.InvalidPrefix == true) { %>
        alert("Please choose a valid prefix for your warranty claim number.");
    <% } %>

    <%if (ViewBag.DupeWaNum == true) { %>
        alert("Warranty Claim Number already exists, please choose another manual WA number or try again.");
    <% } %>

我根本无法重新加载模态中刷新的视图,更不用说更改为绑定模型了。

我知道AJAX调用的第一部分(类型:“GET”)使用URL进入控制器操作GET并返回返回View(模型)然后将其转换为HTML并设置模态窗口HTML它。我一直在假设ajaxSubmit返回到控制器并获取操作的POST版本,并且成功的数据部分:function(data)应该是视图返回,如果条件满足并且构建的JSON URL要重定向如果不是。

我已经尝试将模态html设置为数据并确保满足控制器无效前缀条件,但是模态窗口中的内容似乎永远不会刷新。我还需要弄清楚如何在JQUERY中逻辑告诉控制器是否通过JSON返回了视图或URL,但我认为这并不难理解。

我已经阅读了十几个mvc jquery ajax模式类似的问题,他们帮助但不是

感谢您提供任何帮助,让我了解如何在这里实现目标。

1 个答案:

答案 0 :(得分:1)

对我正在寻找的部分答案进行排序。我意识到现在我的主要障碍是在构建模态窗口之前获得我的测试警报“返回警报(无论如何)”,这显然是返回警报而不是运行其余代码,哑巴。

我现在工作的解决方案是一个非常糟糕的黑客。我让它重建模态并将POST视图数据附加到它。然而,这不是循环所以如果你再次保存并失败我将其设置为警告用户再次保存失败并重试,然后模态关闭,它们可以从头开始。

明天我会看到将其转变为循环结构而不是嵌套结构。

新的“工作”JQuery代码:

var createNewClaimSetup = function () {

    $(selectors.btnCreateNewClaim).live('click', function () {

        var serialNumber = $(this).attr(attributes.serialNumber);
        var spaRegistrationId = $(this).attr(attributes.spaRegistrationId);
        var customerNumber = $(this).attr(attributes.customerNumber);
        var customerStatementName = $(this).attr(attributes.customerStatementName);

        $(selectors.serialNumberHidden).val(serialNumber);
        $(selectors.spaRegistationIdHidden).val(spaRegistrationId);
        $(selectors.customerNumberHidden).val(customerNumber);
        $(selectors.customerStatementName).val(customerStatementName);

        $(selectors.dialog).attr(attributes.title, 'Create New Claim');

        $.ajax ({
            url: inputs.warrantyClaimCreateUrl,
            type: "GET",
            data: {
                   serialNumber: serialNumber,
                   customerNumber: customerNumber
                },
             cache: false,
             success: function (result) {
                $(selectors.dialog).html(result.toString());
                $(selectors.dialog).dialog ({
                     resizable: false,
                    height: 600,
                    width: 850,
                    modal: true,
                    buttons: {
                        'Save': function () {
                        // check to see if a value has been entered for problem description before submitting form
                        //
                        if(!$('#AddProblemModel_ProblemDesc').val().length==0 && (!$('#ClaimPrefix').val().length==0 || $('#chkManualClaimNum').is(':checked')))
                            $(selectors.createNewClaimForm).ajaxSubmit({
                                cache: false,
                                success: function (data) {
                                      if (data.length == 0) {
                                        location.reload();
                                        $(selectors.dialog).dialog('close');
                                    } else if(data.redirectToUrl) {
                                        $(selectors.dialog).dialog('close');
                                        window.location.href = data.redirectToUrl;
                                    } else {
                                        $(selectors.dialog).html(data.toString());
                                        $('#chkManualClaimNum').attr('checked','checked');
                                        $('#manualClaimInfo').toggle();
                                        $(selectors.dialog).dialog ({
                                             resizable: false,
                                            height: 600,
                                            width: 850,
                                            modal: true,
                                            buttons: {
                                                'Save': function () {
                                                    if(!$('#AddProblemModel_ProblemDesc').val().length==0 && (!$('#ClaimPrefix').val().length==0 || $('#chkManualClaimNum').is(':checked')))
                                                    $(selectors.createNewClaimForm).ajaxSubmit({
                                                        cache: false,
                                                        success: function (data) {
                                                              if (data.length == 0) {
                                                                location.reload();
                                                                $(selectors.dialog).dialog('close');
                                                            } else if(data.redirectToUrl) {
                                                                $(selectors.dialog).dialog('close');
                                                                window.location.href = data.redirectToUrl;
                                                            } else {
                                                                alert('Save failed again. Please start over.');
                                                                $(selectors.dialog).dialog('close');
                                                            }
                                                        }
                                                    });
                                                },
                                                Cancel: function () {
                                                    $(this).dialog('close');
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                            else{
                                return alert('You must select a prefix and enter a description for the problem before saving');
                            }
                        },
                        Cancel: function () {
                            $(this).dialog('close');
                        }
                      }
                    });
                }

             });

        });
}

这至少表明如何将POST视图传递回模态窗口。