使用 C# 将 JSON 数据从 asp.net MVC 控制器发送到 highcharts 饼图

发布于 2024-11-13 07:12:38 字数 661 浏览 8 评论 0原文

我想用 C# 从我的 asp.net MVC 控制器发送 json 数据,并使用这些数据绘制 highcharts 饼图。

所以目前我使用这个:

Dictionary<string, double> result = new Dictionary<string, double>();
result.Add("test1", 45);
result.Add("test2", 64);

var jsonResult = Json(new
{
    graphDivId = "divGraph",
    legend = "A legend",
    stats = result ,
});

jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsonResult;

但是当我通过 jquery 中的 ajax 调用接收数据时,我有这个:

stats:[{"Key":"test1","Value":45},{"Key":"test2","Value":64}]

但是我需要这个:

stats:[["test1",45],["test2",64]]

有什么想法吗?

I want to send json data from my asp.net MVC controller in C# and use those datas to draw a highcharts pie chart.

So for the moment I use this :

Dictionary<string, double> result = new Dictionary<string, double>();
result.Add("test1", 45);
result.Add("test2", 64);

var jsonResult = Json(new
{
    graphDivId = "divGraph",
    legend = "A legend",
    stats = result ,
});

jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return jsonResult;

but when I received data by an ajax call in jquery I have this :

stats:[{"Key":"test1","Value":45},{"Key":"test2","Value":64}]

but I need this :

stats:[["test1",45],["test2",64]]

Any ideas ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

回忆追雨的时光 2024-11-20 07:12:38

今天早上我在玩这个,我想出了下面的内容 - 但它不会工作,因为你会得到 [{x:"testx", y:60}....]。所以这样不好。不过,您也许可以使用它并重写 SimpleClass 上的 ToJSON 方法。

我的另一个想法(我不确定它是否有效)是拥有一个 ArrayList 的集合。由于 ArrayList 不是强类型,因此您可以向它们添加 string 和 double 属性。

让我知道结果如何。

如果您使用简单对象的列表会怎样?您也许可以使用键值对或其他一些现有类。但是您可以创建一个简单的类来保存您的数据。

   class SimpleClass{
       public int x{set; get;}
       public double y{set; get;}
   } 

    var results = new List<SimpleClass>();
    results.Add(new SimpleClass{x="test3", y=42});        
    results.Add(new SimpleClass{x="test2", y=99});

I was playing with this a little this morning and I came up with what i have below-- but it won't work because you'll get [{x:"testx", y:60}....]. So that's no good. You might be able to use it though and override a ToJSON method on the SimpleClass.

One other thought I had (and I'm not sure it would work) is to have a collection of ArrayList's. Since ArrayList's are not strongly type, you can add a string and double property to them.

Let me know how this turns out.

What if you used a list of Simple objects. You might be able to use a key value pair or some other existing class. But you could create a simple class which will hold your data.

   class SimpleClass{
       public int x{set; get;}
       public double y{set; get;}
   } 

    var results = new List<SimpleClass>();
    results.Add(new SimpleClass{x="test3", y=42});        
    results.Add(new SimpleClass{x="test2", y=99});
各空 2024-11-20 07:12:38

完美 ek_ny !

感谢您的帮助,我找到了如何在没有特定课程的情况下进行操作:

var results = new List<List<object>>();
results.Add(new List<object>(new object[]{"test1", 45}));
results.Add(new List<object>(new object[]{"test2", 99}));

perfect ek_ny !

Thanks to your help I found how to do also without a specific class :

var results = new List<List<object>>();
results.Add(new List<object>(new object[]{"test1", 45}));
results.Add(new List<object>(new object[]{"test2", 99}));
悲凉≈ 2024-11-20 07:12:38

另一件事很高兴知道。

highcharts series.data 是一个点对象,您可以在 C# 中用此表示:

class HighChartsPoint
{
    public double x {set; get;}
    public double y {set; get;}
    public string color {set; get;}
    //public HighChartsEvent events{set; get;}
    public string id {set; get;}
    //public HighChartsMarker marker {set; get;}
    public string name {set; get;}
    public bool sliced {set; get;}
} 

参考: http://www .highcharts.com/ref/#point

ek_ny 类是点对象表示的一部分。
事件和标记被注释,因为它是另一个要编写的类。它的代表在那里:

事件:http://www.highcharts.com/ref/#point -事件

标记:http://www.highcharts.com/ref/#point -marker

所以现在你可以这样使用它:

var results = new List<HighChartsPoint>();
results.Add(new HighChartsPoint {
          name="test3", 
          y=42, 
          color="red", 
          id="someid", 
          sliced=false 
        });

var jsonResult = Json(results);
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet; 
return jsonResult;

希望它有帮助......

Another thing nice to know.

highcharts series.data is a point object which you can represent by this in C# :

class HighChartsPoint
{
    public double x {set; get;}
    public double y {set; get;}
    public string color {set; get;}
    //public HighChartsEvent events{set; get;}
    public string id {set; get;}
    //public HighChartsMarker marker {set; get;}
    public string name {set; get;}
    public bool sliced {set; get;}
} 

reference : http://www.highcharts.com/ref/#point

ek_ny class is a part of point object representation.
events and marker is commented because it's another class to write. Representation of it is there :

events : http://www.highcharts.com/ref/#point-events

marker : http://www.highcharts.com/ref/#point-marker

So now you can use it like that :

var results = new List<HighChartsPoint>();
results.Add(new HighChartsPoint {
          name="test3", 
          y=42, 
          color="red", 
          id="someid", 
          sliced=false 
        });

var jsonResult = Json(results);
jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet; 
return jsonResult;

Hope it help...

怪异←思 2024-11-20 07:12:38

万一。如果值设置为空,Highcharts 将无法显示图表。
并且asp.net mvc控制器类的Json方法无法过滤空值。

为此,您可以使用 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.net mvc 的 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.Net DefaultValue 属性:

[DefaultValue(null)]

Just in case. Highcharts can't display chart if value are set to null.
And Json method of asp.net mvc controler class can't filter null value.

For that you can use json.net library and create, for example, a JsonNetResult (inherit from 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();
            }
        }
    }

and then add this method to your controler to replace Json method of asp.net mvc :

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;
        }

So now you can use it in your controler action like that :

public JsonNetResult MyAction()
{
    MyClass myObject = new MyClass();
    return JsonNet(myObject);
}

Ah and an other thing, don't hesitate to use Json.Net DefaultValue attribute on MyClass properties :

[DefaultValue(null)]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文