JsonResult为Jquery .ajax返回null

我正在尝试将一个Jquery .ajaxpost发送到MVC操作。 这个Action然后应该返回一个JsonResult。 目前,这个JsonResult是“”,但我希望返回对象用Json填充。 有帮助吗? 谢谢!

$.ajax({ type: 'post', dataType: 'json', url: url, contentType: "application/json; charset=utf-8", traditional: true, data: JSON.stringify({ source: source }), success: function (data) { debugger; } }); public ActionResult PublishSource(string source) { return Json(new {data = "test"}); } 

编辑:这是我目前的代码。 仍然在.ajax的成功方法中返回数据为空。

 $.ajax({ type: 'post', cache: false, url: url, contentType: "application/json", success: function (data) { debugger; } }); public JsonResult PublishSource() { var data = "test"; return Json(data, JsonRequestBehavior.AllowGet); } 

像下面一样更改控制器操作

 public JsonResult PublishSource(string source) { var data="test"; return Json(data,JsonRequestBehaviour.AllowGet); } 

试试这个,看它是否有效:

 return Json(new {dataObject = data}, JsonRequestBehavior.AllowGet); 

然后在成功时你得到这样的数据:

  success: function (data) { debugger; var returnedData = data.dataObject; } 

在控制器返回之前与JSON Result OK有相同或类似的问题,但是当它达到ajax成功回调时为NULL。

原来这不是调用的问题,而是模型上的访问修饰符,它被控制器转换为JSON结果。 将此设置为public,结果回调中的结果不再为NULL。

希望这可以帮助处于同样情况下的任何人尝试过其他答案。

使用JSON.NET作为默认的Serializer来序列化JSON而不是默认的Javascript Serializer:

这将处理发送数据的情况,如果它的NULL。

你需要在你的动作方法中写这个:

 return Json(data, null, null); 

注意:上面函数中的第2和第3个参数null是为了方便Controller类中Json方法的重载。

下面是JsonNetResult类的代码。

 public class JsonNetResult : JsonResult { public JsonSerializerSettings SerializerSettings { get; set; } public Formatting Formatting { get; set; } public JsonNetResult() { SerializerSettings = new JsonSerializerSettings(); JsonRequestBehavior = JsonRequestBehavior.AllowGet; } public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); HttpResponseBase response = context.HttpContext.Response; response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting.Indented }; JsonSerializer serializer = JsonSerializer.Create(SerializerSettings); serializer.Serialize(writer, Data); writer.Flush(); } } 

此外,您需要在BaseController中添加以下代码(如果项目中有任何代码):

  ///  /// Creates a NewtonSoft.Json.JsonNetResult object that serializes the specified object to JavaScript Object Notation(JSON). ///  ///  ///  ///  /// The JSON result object that serializes the specified object to JSON format. The result object that is prepared by this method is written to the response by the ASP.NET MVC framework when the object is executed. protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding) { return new JsonNetResult { Data = data, ContentType = contentType, ContentEncoding = contentEncoding }; }