将jquery对象传递给MVC操作

时间:2012-03-19 22:38:34

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

我正在尝试使用.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);
        }
    }

3 个答案:

答案 0 :(得分:0)

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

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

尝试使用(int,People)签名创建一个控制器方法,看看它是否适合你。

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

答案 1 :(得分:0)

尝试从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));
    }
})

答案 2 :(得分:0)

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