【问题标题】:JsonResult returns null for Jquery .ajaxJquery .ajax 的 JsonResult 返回 null
【发布时间】:2014-05-17 06:00:26
【问题描述】:

我正在尝试将 Jquery .ajax 发布到 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 为 null 的成功方法中返回数据。

$.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 ActionResult PublishSource(string source) 更改为 public JsonResult PublishSource(string source). 内容类型错误以及将其更改为 contentType: 'application/json'
  • 在成功方法中我正在获取数据 = ""
  • 我不确定问题出在哪里,但也许是因为你有传统的:真的?我在整个代码中都使用 JsonResults,并且不设置它或内容类型。
  • 我添加了缓存:假并取出了传统:真,但仍然没有运气。我没有为 Jquery Get 返回 Json 数据的问题,仅适用于 Jquery Post

标签: jquery asp.net-mvc


【解决方案1】:

如下所示更改您的控制器操作

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

【讨论】:

  • 我添加了这个,但仍然没有运气。这是我当前的代码。现在成功方法没有命中。 $.ajax({ type: 'post', dataType: 'json', url: url, contentType: "application/json", data: JSON.stringify({ source: source }), success: function (data) { debugger ; } });
  • 是的,我也编辑了控制器动作。我已将更新的代码放在顶部
【解决方案2】:

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

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

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

        success: function (data) {
            debugger;

var returnedData = data.dataObject;
        }

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:

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

      如果它为NULL,这将处理发送数据的场景。

      你需要在你的action方法中写下这个:

      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 中添加以下代码:

          /// <summary>
          /// Creates a NewtonSoft.Json.JsonNetResult object that serializes the specified object to JavaScript Object Notation(JSON).
          /// </summary>
          /// <param name="data"></param>
          /// <param name="contentType"></param>
          /// <param name="contentEncoding"></param>
          /// <returns>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.</returns>
          protected override JsonResult Json(object data, string contentType, System.Text.Encoding contentEncoding)
          {
              return new JsonNetResult
              {
                  Data = data,
                  ContentType = contentType,
                  ContentEncoding = contentEncoding
              };
          }
      

      【讨论】:

        猜你喜欢
        • 2011-08-14
        • 2015-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多