1

What I'm trying to do: Create a chart and have it display data from the server (held in a C# object) every x mminutes. From googling using JSON (which I've never used before) would be best practice.

What I have so far: I have the backend C# (using MVC 5) getting the correct data, lots of objects with lots of properties, some I want to display in the chart, others I don't.

I'v also started on a JSON function in my Index.cshtml which is where my graph is (currently set with static data, it's a simple jQuery plug-in).

The problem: Unsure how to get specific object properties, to the JSON data and then to the chart data.

What would be the best way of achieving this?

Code: Controller:

// GET: Graphs
        public ActionResult Index()
        {
            return View();
        }

        public static List<server> GetServer()
        {
            Api api = new Api();
            List<server> sList = api.GetServerStats();
            return sList;
        }

Script in INdex:

<script src="~/Scripts/canvasjs.min.js"></script>
<script type="text/javascript">
    window.onload = function () {
        var chart = new CanvasJS.Chart("someChart", {
            title: {
                text: "Space left on Server vs Total"
            },

            data: [
            {
                type: "column",
                name: "Totals",
                showInLegend: true,
                dataPoints: [
                { label: "Space", y: 20 }
                ]
            },

           {

               type: "column",
               name: "Used",
               showInLegend: true,
               dataPoints: [
               { label: "Space", y: 10 }
               ]
           }
            ],
            axisY: {
                prefix: "",
                suffix: "GB"
            }
        });

        chart.render();
    }

    $(document).ready(function () {
        window.onload(function () {
            $.ajax({
                type: "POST",
                url: "GraphController/GetServer",
                data: { someParameter: "some value" },// array of values from object or just object
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (result) {
                    // need to push into jQuery function
                }
            });
        });
    });
</script>
4
  • What does the GetStuff action return? Commented Jun 12, 2015 at 8:06
  • Crap, sorry that should be GetServer - will edit. Commented Jun 12, 2015 at 8:07
  • If you have lots of properties you know you won't want to chart, you might want to consider adding [JsonIgnore] to these properties, in your server object, so that they won't be serialized. Either that, or creating a viewmodel of only the data you're insterested in (which you could, if you want, set up to adhere to the CanvasJS format, so you don't need to process the data client side) Commented Jun 12, 2015 at 8:09
  • Thanks for the suggestion of serveral View Models, David, but I will want most of them, just not for my initial chart. Want to keep it simple initially to see how it's all working, then I can play around with it and display the other properties on other charts on the page. Commented Jun 12, 2015 at 8:12

2 Answers 2

1

Returning a serialised list of objects couldn't be easier with MVC, it takes a lot of the heavy lifting out of it for you if you just return a JsonResult:

public ActionResult GetServer() {
  var api = new Api();
  var = api.GetServerStats();  
  return Json(sList);
}

Debug the success of your ajax call to find out if result is what you want and expect, and then pass it to your chart script.

NOTE: From your use of wording (i.e. 'lots'), I'd recommend cutting down your list of server properties you return to your view. This is a perfect candidate for creating what's called a view model. This view model would be a kind of 'lite' version of your full server object. It would improve efficiency of serialisation for starters and, semantically, makes more sense.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, looking into this now, in the first sentence you use JsonResult (which is the type I find and can't be used as a variable) but in your example you use Json - is that correct?
Nearly correct, it looks misleading but I'm not returning Json, I'm returning the return type/result of a Json method call. This method is found in the base class Controller. At the top where you've extended Controller (where it says YourClass : Controller), right click on Controller and 'Go to Definition', you'll notice a method signature in there for Json, and it returns a JsonResult object.
Ah yes - thanks, one more thing, how can I get the JSON to repeat every x minutes?
Run x minutes: first, refactor to named functions rather than inline functions, then setTimeout(loadFunc, 1000*minutes). Yes, without the brackets, or, if you prefer: setTimeout(function() { loadFunc(); }, 1000*minutes)
0

I was doing same thing with highcharts and here is an approximate solution for you:

    public ActionResult GetServer()
    {
        Dictionnary<server> sList = new Dictionnary<string,object>();
        sList.Add("Totals",new{
            type= "column",
            name= "Totals",
            showInLegend= true,
            dataPoints= new List<dynamic>(){
              new{ label= "Space", y= 20}/*,
              new{ label= "label2", y= 30},*/
             }
            });

        sList.Add("Totals",new{
            type= "column",
            name= "Used",
            showInLegend= true,
            dataPoints= new List<dynamic>(){
              new{ label= "Space", y= 10}/*,
              new{ label= "label2", y= 40},*/
             }
            });
       return Json(sList, "text/json", JsonRequestBehavior.AllowGet);
    }

Change window.onload=function(){} in

function drawChart(serverData){
  var chart = new CanvasJS.Chart("someChart", {
        title: {
            text: "Space left on Server vs Total"
        },

        data: serverData,
        axisY: {
            prefix: "",
            suffix: "GB"
        }
    });

    chart.render();
}
  $(document).ready(function () {
        $.ajax({
            type: "POST",
            url: "GraphController/GetStuff",
            data: { someParameter: "some value" },
            // array of values from object or just object
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (serverData) {
                // need to push into jQuery function
                drawChart(serverData);
            }
        });
});

5 Comments

Thanks, ran your code against my own but where you have return Json(sList, "text/json", JsonRequestBehavior.AllowGet); I get the error Cannot implicity convert type yet these are still objects which you've shown you have in your code, did you come across this issue? - ignore sorted.
can you please edit your question and provide api.GetServerStats(); function code? I'd like to see what you are returning there inside
Unfortunately I don't have access to that as it's reference from another company's API, effectively I listen, and it sends stats, not from my server, but from my web server's built in API, so all I have is a list of Properties within the function GetServerStats along with un/pw/url to specify that it's me. I don't do the heavy lifting.
Okay I see! but you need to know the format of data being returned by your company. is that a list? if yes: is that a List<of What Type> ?
It's a list of Server Type objects, which are just containers for lots of Properties containing the server data which they hold at their end.So when I hover over the Function it just shows all of the properties within the object and their corresponding values.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.