【问题标题】:Avoid returning nulls in JSON for AJAX calls避免在 JSON 中为 AJAX 调用返回空值
【发布时间】:2012-02-21 00:12:34
【问题描述】:

我有以下方法:

[HttpPost]
[AjaxOnly]
public JsonResult ValidateInput(string text)
{
    return new EmptyJsonResult();
}

/// <summary>
/// returns a JSON result that is marked as being empty.
/// </summary>
public sealed class EmptyJsonResult : JsonResult
{
    public EmptyJsonResult()
    {
        Data = new JsonResultData
        {
            Empty = true
        };
    }
}

public class JsonResultData
{
    public bool Empty { get; set; }
    public string[] Errors { get; set; }
}

我预计这会将{"Empty":true} 返回到浏览器,但它却返回{"Empty":true,"Errors":null}

我可以设置任何属性或一些东西以避免在我没有填充的对象上返回空值吗?

【问题讨论】:

  • 你想填充什么值?你总是可以为每个对象编写自己的 getter,但是 null 是可以的
  • 也许你应该看看源代码,看看你是否可以改变一些东西。这是一个围绕该领域深入研究的 SO 问题:stackoverflow.com/questions/8833961/…
  • 我将如何在这里实现NullValueHandling.Ignore

标签: c# jquery ajax model-view-controller


【解决方案1】:

如果你只是返回一个匿名对象,对你有什么不同吗?

    public EmptyJsonResult()
    {
    Data = new
        {
            Empty = true
        };
    }

【讨论】:

    【解决方案2】:

    我没有看到返回 null 的问题,但是如果您需要实现您的目标,请拥有一个名为 JsonResultData 的接口和两个实现它的类。一个具有您需要返回的所有属性,而第二个只有 Empty。

    【讨论】:

      猜你喜欢
      • 2012-12-05
      • 1970-01-01
      • 2013-01-03
      • 2011-05-17
      • 2012-03-16
      • 1970-01-01
      • 2015-10-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多