【问题标题】:Passing jquery object to MVC action将 jquery 对象传递给 MVC 操作
【发布时间】:2012-03-19 22:38:33
【问题描述】:

我正在尝试使用 .ajax()People 对象发布到需要 ViewModel 作为参数的 MVC2 操作。 ViewModel 有一个People 属性。

问题是当MVC动作被激活时,ajax()回发People对象总是空的。我使用 Fiddler 来诊断问题。 People 对象中的属性值都包含在标头中。这是我的客户端 jQuery 脚本。请注意,我使用了三种方法将属性值填充到 People 对象中,但它们都不起作用。

        StaffDlg.delegate("#SaveButton", "click",
        function (e) {
            e.preventDefault();

            People["PKey"] = $("#PKey").val();
            People["FName"] = $("#FName").val();
            People["LName"] = $("#LName").val();
            People["MName"] = $("#MName").val();
            People["SSN"] = $("#SSN").val();
            People["Gender"] = $("#Gender").val();
            People["DOB"] = $("#DOB").val();
            People["BirthPlace"] = $("#BirthPlace").val();
            People["NetworkAccount"] = $("#NetworkAccount").val();

            var pkey = $("#PKey").val();
            var action;

            if (!isNaN(parseFloat(pkey)) && isFinite(pkey)) {
                action = "Edit" + "/" + pkey;
            }
            else {
                action = "Create";
            }

            $.ajax({
                url: getRootUrl() + "/Staff/" + action,
                //data: { FName: $("#FName").val(), LName: $("#LName").val(), MName: $("#MName").val(),
                //  SSN: $("#SSN").val(), Gender: $("#Gender").val(), DOB: $("#DOB").val(),
                //  BirthPlace: $("#BirthPlace").val(), NetworkAccount: $("#NetworkAccount").val()
                //},
                //data: JSON.stringify(People),
                data: $("Form").serialize(),
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                success: function (result) {
                    $("#ajaxResponse").addClass("whiteOnGreen").html("Update succeeded");
                },
                error: function (qXHR, textStatus, errorThrown) {
                    $("#ajaxResponse").addClass("whiteOnRed").html("Failed to save the record!\r\n" +
                        textStatus + ": " + errorThrown + "\r\n" +
                        "data : " + JSON.stringify(People));
                }
            })
        } 
    );    

这是 MVC 操作。

public ActionResult Edit(int id, StaffViewModel updatedStaff)
    {
        People staff = _staffService.GetStaff(id);

        if (updatedStaff == null)
            return View("NotFound");
        if (ModelState.IsValid)
        {
            TryUpdateModel<People>(staff, "staff"); 
            staff.RecordLastUpdated = DateTime.Now;
            staff.UpdatedBy = HttpContext.User.Identity.Name;
            _staffService.SaveStaff();
            //return RedirectToAction("Index", new { id = thisStaff.PKey });

            if (Request.IsAjaxRequest())
                return this.Json(staff, JsonRequestBehavior.AllowGet);
            else
            {
                if (string.IsNullOrEmpty(updatedStaff.previousURL))
                    return Redirect("/Staff/Startwith/" + staff.LName.Substring(1, 1));
                else
                    return Redirect(updatedStaff.previousURL);
            }
        }
        else
        {
            if (Request.IsAjaxRequest())
            {
                string errorMessage = "<div class='whiteOnRed error'>"
                    + "The following errors occurred:<ul>";
                foreach (var key in ModelState.Keys)
                {
                    var error = ModelState[key].Errors.FirstOrDefault();
                    if (error != null)
                    {
                        errorMessage += "<li>"
                            + error.ErrorMessage + "</li>";
                    }
                }
                errorMessage += "</ul></div>";
                return Json(new { Message = errorMessage });
            }
            else
                return View(updatedStaff);
        }
    }

【问题讨论】:

标签: ajax asp.net-mvc-2 jquery


【解决方案1】:

您声明表单需要 StaffViewModel 作为参数,并且 StaffViewModel 具有 People 属性...但是您没有传递完整的 StafFViewModel 对象 - 相反,您从 Ajax 调用传递了 People 对象,并希望People 属性在 MVC 端填充。

那里有一个断开连接,自动绑定器不知道如何桥接它。

尝试创建一个带有 (int, People) 签名的控制器方法,看看是否适合您。

否则,您可能需要创建自定义活页夹。

【讨论】:

  • 根据stackoverflow.com/questions/1160669/…这个帖子,也不需要创建。 MVC 应该能够深入到 ViewModel 中的 People 属性,并将其属性与 .ajax() 发布的 People 绑定。
【解决方案2】:

尝试从您的 ajax 调用中删除 dataType 和 contentType 设置:

$.ajax({
    url: getRootUrl() + "/Staff/" + action,
    data: $("Form").serializeArray(),
    type: "POST",
    success: function (result) {
        $("#ajaxResponse").addClass("whiteOnGreen").html("Update succeeded");
    },
    error: function (qXHR, textStatus, errorThrown) {
        $("#ajaxResponse").addClass("whiteOnRed").html("Failed to save the record!\r\n" +
            textStatus + ": " + errorThrown + "\r\n" +
            "data : " + JSON.stringify(People));
    }
})

【讨论】:

  • 我将表单数据 ajaxed 到 MVC Edit(int id, StaffViewModel updatedStaff) 操作。但是,我仍然无法将表单数据 ajaxed 到 Create(People person) 操作。 .ajax() 检查 $("#PKey").val() 以确定要发布的操作。您知道为什么 Create 操作没有拾取它吗? Edit() 接受 ViewMode 而 Create() 只接受 People 实体是否重要?谢谢。
【解决方案3】:

我解决了 .ajax() 没有将表单值发布到 MVC Create(People person) 操作的问题。这是与 Edit(StaffViewModel) 中使用的参数类型不同的参数类型。现在这两个操作都接受相同类型的参数 StaffViewMode。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-02
    • 1970-01-01
    • 2020-05-11
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多