AJAX发布请求不返回JSON数据

时间:2014-10-07 15:33:30

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

这是我的AJAX请求:

var data = modalDom.find("form").serializeObject();
data["returnJson"] = true;

$.ajax({
    type: "POST",
    url: "/companies/edit/",
    data: data,
    dataType: "JSON",
    success: function (result) {
        modalDom.modal('hide');

        var dropdown = $("#create-modal #CompanyID");
        var currentSelected = dropdown.find("option:selected");
        if (currentSelected.length) {
            currentSelected.removeAttr("selected");
        }

        var newOption = '<option value="' + result.company.CompanyID + '">' + result.company.Name + '</option>';
        dropdown.append(newOption);
        dropdown.val(result.company.CompanyID);
    }
});

这是它正在击中的控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Company company) {
    if (CurrentUser.IsCompany(User)) {
        return AjaxJsonResult.AuthFailResult();
    }

    if (!ModelState.IsValid) {
        return AjaxJsonResult.FailResult(ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage).ToList());
    }

    db.Company_CompanyType.RemoveRange(db.Company_CompanyType.Where(c => c.CompanyID == company.CompanyID));
    if (Request.Params["CompanyTypes[]"] != null) {
        var companyTypes = (from item in Request.Params["CompanyTypes[]"].Split(new[] {','})
            select db.CompanyTypes.FirstOrDefault(c => c.Name == item)
            into ct
            where ct != null
            select new Company_CompanyType() {
                CompanyID = company.CompanyID, CompanyTypeID = ct.CompanyTypeID
            }).ToList();

        db.Company_CompanyType.AddRange(companyTypes);
    }

    if (company.CompanyID <= 0) {
        db.Companies.Add(company);
    }
    else {
        db.Entry(company).State = EntityState.Modified;
    }

    db.SaveChanges();

    return AjaxJsonResult.SuccessResult("?companyID=" + company.CompanyID);
}

我无法通过结果变量访问我的JSON对象的任何属性。当我记录我在控制台中传递的数据时,它是来自表单的正确数据。在控制台中记录结果变量时,我得到了这个:

Object {Success: true, RedirectTo: "?companyID=9818", Messages: null}

我做错了什么?

编辑:我的目标是让结果对象返回从表单提交的数据。例如:

result.company.CompanyID = 1988
result.company.Name = "My Company Name"

AjaxJsonResult.SuccessResult()方法的源代码:

public class AjaxJsonResult {
    public bool Success { get; set; }
    public string RedirectTo { get; set; }
    public List<string> Messages { get; set; }

    public static JsonResult SuccessResult(string redirectTo) {
        var result = new AjaxJsonResult {
            Success = true,
            RedirectTo = redirectTo,
            Messages = null
        };
        return ToJsonResult(result);
    }

    public static JsonResult ToJsonResult(AjaxJsonResult result, JsonRequestBehavior behavior = JsonRequestBehavior.AllowGet) {
        return new JsonResult() {
            Data = result,
            ContentType = (string) null,
            ContentEncoding = (Encoding) null,
            JsonRequestBehavior = behavior
        };
    }
}

1 个答案:

答案 0 :(得分:1)

javascript可用的json对象只能与控制器序列化的对象具有相同的属性。因此,如果您返回AjaxJsonResult,则只能访问result.Successresult.RedirectToresult.Messages。如果您需要序列化公司对象,您有两个选择:

  1. 返回普通JsonResult但未成功,重定向和消息信息,只需依赖http状态代码。这将涉及更改操作方法,如果您在javascript中使用成功,重定向和消息数据,它将无法工作。
  2. 更新AjaxJsonResult,以便它有一个额外的属性来存储内容,并在SuccessResult方法中传递它。它可以强类型化为Company类,也可以是普通对象。
  3. 以下是一个例子:

     public static JsonResult SuccessResult(string redirectTo, object data) 
     {
         var result = new AjaxJsonResult 
         {
             Data = data,
             Success = true,
             RedirectTo = redirectTo,
             Messages = null
         };
         return ToJsonResult(result);
     }
    

    然后你必须像这样传递方法中的对象:

    return AjaxJsonResult.SuccessResult("?companyID=" + company.CompanyID, new {company});
    

    然后,您就可以在javascript中访问对象的属性,但是您必须注意使用适当的大小写并添加新的Data属性。如果您这样做,您可以通过输入result.Data.company.CompanyID

    来获取公司ID