這裏是我的AJAX請求:AJAX POST請求不返回JSON數據
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);
}
});
這裏是它的擊球控制器:我無法訪問我的JSON對象的任何屬性
[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);
}
通過結果變量。當我記錄我在控制檯傳遞的數據時,它是來自表單的正確數據。當在控制檯中記錄結果變量時,我得到:
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
};
}
}
得到公司ID你能舉一個你想要結果json數據看起來像什麼樣子的例子嗎? – elolos 2014-10-07 15:36:04
@elolos我對原始文章進行了一些編輯。希望這可以讓我們更清楚一點。 – mdk09 2014-10-07 15:42:56
謝謝,這澄清了你試圖達到的目標。你能否也請發佈'AjaxJsonResult.SuccessResult()'方法的源代碼? – elolos 2014-10-07 15:49:43