念のため。値がnullに設定されている場合、Highchartsはチャートを表示できません。また、asp.netmvcコントローラークラスのJsonメソッドはnull値をフィルター処理できません。
そのためには、json.netライブラリを使用して、たとえばJsonNetResult(ActionResultから継承)を作成できます。
public class JsonNetResult : ActionResult
{
public Encoding ContentEncoding { get; set; }
public string ContentType { get; set; }
public object Data { get; set; }
public JsonSerializerSettings SerializerSettings { get; set; }
public Formatting Formatting { get; set; }
public JsonNetResult()
{
SerializerSettings = new JsonSerializerSettings();
}
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;
if (Data != null)
{
JsonTextWriter writer = new JsonTextWriter(response.Output) { Formatting = Formatting };
JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
serializer.Serialize(writer, Data);
writer.Flush();
}
}
}
次に、このメソッドをコントローラーに追加して、asp.netmvcのJsonメソッドを置き換えます。
protected JsonNetResult JsonNet(object data, bool needDefaultSettings)
{
var result = new JsonNetResult();
result.Data = data;
if (needDefaultSettings)
{
var defaultSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
DefaultValueHandling = DefaultValueHandling.Ignore
};
result.SerializerSettings = defaultSettings;
}
return result;
}
だから今、あなたはそのようなあなたのコントローラーアクションでそれを使うことができます:
public JsonNetResult MyAction()
{
MyClass myObject = new MyClass();
return JsonNet(myObject);
}
ああ、他のことですが、MyClassプロパティでJson.NetDefaultValue属性を使用することを躊躇しないでください:
[DefaultValue(null)]