开发者

How to return JSON in specific format in ASP.NET MVC using Json() with no property names

开发者 https://www.devze.com 2022-12-21 23:12 出处:网络
I am using a charting javascript library that expects its data in a specific JSON format - without property names.

I am using a charting javascript library that expects its data in a specific JSON format - without property names. I have an object in my Model that I am using to return the data to the charts. This looks as follows:

public class ChartData
{
    public string Key { get; set; }
    public int Value { get; set; }
}

An action looks as follows:

public ActionResult AssetsPerFloor(Guid id)
    {
        var 开发者_如何转开发results = from a in surveyRepository.GetAssetsForBuidling(id)
                      group a by a.Room.Floor into g
                      select new ChartData{ Key = g.Key.ToString(), Value = g.Count() };
        return Json(results);
    }

This returns JSON in the format [{"Key":"Main Building","Value":1}]

However, the chart requires no property names, eg: [[5, 2], [6, 3], [8, 2]]

Is there anyway I can return the results in this format. I'm sure there's a simple trick to it, but I cant think of it.


As far as I understand, it needs to return a multi-dimensional array. Try this :

var results = 
    (from a in surveyRepository.GetAssetsForBuidling(id)
        group a by a.Room.Floor into g
        select new ChartData{ Key = g.Key.ToString(), Value = g.Count() })
        .Select(x => new string[] { x.Key, x.Value.ToString() };
return Json(results);
0

精彩评论

暂无评论...
验证码 换一张
取 消