【问题标题】:JsonResult - how to return an empty JSON result?JsonResult - 如何返回一个空的 JSON 结果?
【发布时间】:2014-02-25 21:05:42
【问题描述】:

我有一个 ajax 调用,它向我的控制器操作方法之一发出 GET 请求。

ajax 调用应该获得 JSON 响应并使用它来填充数据网格。回调函数应该触发并构建网格并隐藏加载指示器。

$.getJSON('@Url.Action("Data", "PortfolioManager")' + '?gridName=revenueMyBacklogGrid&loginName=@Model.currentUser.Login', function (data) {

                        ConstructrevenueMyBacklogGrid(data);
                        $('#revenueMyBacklogLoadingIndicator').hide();

                    });

问题是当我转换为 JsonResult 对象的对象没有数据时 - 它只是一个空集合。

returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);

在此示例中,集合 myYTDSalesClients 返回空(这没问题且有效 - 有时不会有任何数据)。

然后 JSON 对象返回一个空响应(空白,nadda),由于它不是有效的 JSON,回调函数不会触发。因此,加载指示器仍然显示,看起来就像永远加载一样。

那么,如何返回一个空的 JSON 结果 {} 而不是空白?

【问题讨论】:

    标签: jquery json asp.net-mvc-4


    【解决方案1】:

    从 asp.net mvc 5 开始,您可以简单地编写:

    Json(new EmptyResult(), JsonRequestBehavior.AllowGet)
    

    【讨论】:

      【解决方案2】:
      if (portfolioManagerPortalData.salesData.myYTDSalesClients == null) {
          returnJsonResult = Json(new object[] { new object() }, JsonRequestBehavior.AllowGet);
      }
      else {
          returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);
      }
      

      【讨论】:

      • 嘿,太棒了。不幸的是,它告诉我它无效。它正在返回 {}。我想我需要 [{}]。有什么想法吗?
      • 好吧,我是个白痴。这完全是另外一回事。但!如果有人需要的话,我确实想出了 [{}] 的东西...returnJsonResult = Json(new object[] { new object() }, JsonRequestBehavior.AllowGet);
      【解决方案3】:

      在 .Net Core 3.0 中,对于 ControllerBase 类型的控制器,您可以这样做:

      return new JsonResult(new object());
      

      【讨论】:

        【解决方案4】:

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

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

        例如

        在你的操作方法中代替这个:

        return Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet)
        

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

        return Json(portfolioManagerPortalData.salesData.myYTDSalesClients, null, null);
        

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

        此外,您不需要在上述所有操作方法中检查 null:

                if (portfolioManagerPortalData.salesData.myYTDSalesClients == null)
                {
                    returnJsonResult = Json(new object[] { new object() }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    returnJsonResult = Json(portfolioManagerPortalData.salesData.myYTDSalesClients, JsonRequestBehavior.AllowGet);
                }
        

        下面是 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
                };
            }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-08-19
          • 1970-01-01
          • 1970-01-01
          • 2020-09-06
          • 2021-02-20
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多