虽然发回响应并检查回调中的数据对象(如上面@Richard 和@Jatin 所解释的那样)会起作用,但我倾向于遵循以下模式滚动我自己的 AjaxResult 对象,用模型状态有效性水合这个对象,成功状态,以及我需要传回 $.ajax 成功回调函数的任何数据。这为处理 $.ajax 请求提供了一个灵活而优雅的解决方案。例如:
// custom ajax request result class
public class AjaxResult
{
public bool IsValid { get; set; }
public bool Success { get; set; }
public string Message { get; set; }
public Dictionary<string, object> Data { get; set; }
public AjaxResult()
{
Data = new Dictionary<string, object>();
}
public void AddData(string dataKey, object dataValue)
{
if (dataKey != null && !Data.ContainsKey(dataKey))
{
Data.Add(dataKey, dataValue);
}
}
}
// controller
public ActionResult NhpdAdminRejectAddress(NhpdAdminViewModel model)
{
AjaxResult result = new AjaxResult();
if (ModelState.IsValid)
{
// do something
result.AddData("Code", -1);
result.IsValid = true;
result.Success = true;
}
return Json(result);
}
// ajax post request
$.ajax({
type: "POST",
url: '@Url.Action("NHPDAdminRejectAddress", "Home")',
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result != null && result.Data != null && result.Data.Code != null)
{
int code = result.Data.Code;
}
},
error: function () {
// handle error
}
});