1

I am trying to take a List of a custom class and convert it to JSON in MVC/C#. I have used both json.encode and javascriptserializer to no avail. The json data is shown with &.quot; instead of the single or double quotes. Here's what I believe is the relevant code. This data is going to be used in a highcharts application.

My Models

public class DataPoint
{
    public double? data { get; set; } //CTDI value
    public DateTime? DateOfScan { get; set; }
    public string Name { get; set; }
    public string Nmmber{ get; set; }
    public int PersonDatabaseID { get; set; }
    public string EquipmentName{ get; set; }
}

public class PlotData : List<DataPoint>
{
}

public class PlotListModel : List<PlotData>
{
}

My View

foreach (PlotData pd in (PlotListModel) ViewBag.MyData)
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    var jsData1 = js.Serialize(pd);

    //Or use JSON.Encode
    var jsData2 = Json.Encode(pd);

    string divID = "container" + i;
    <div id='@divID'>
        <script type='text/javascript'>
            $(function () {
                var chart = new Highcharts.Chart({
                    chart: {
                        renderTo: '@divID',
                        type: 'colummn'
                    },
                    title: {text: '@divID'},
                    tooltip: {
                        formatter: function () {
                            return 'Extra data: <b>' + this.point.Scanner + '</b>';
                        }
                    },

                    series: [{
                        name: 'Foo',
                        data: ['@jsData1']
                    }]
                });
            });
        </script>
    </div>

    i += 1;
}

When I look at the page source I see the data fields and values surrounded by the encoded quote value - &quot;
3
  • You should definitely use Web API to serialize the Data into JSON format and request it from the server via ajax call Commented Jul 8, 2015 at 16:51
  • Thanks, Thomas. Any suggestions on a good tutorial on that? Have no idea where to start with that other than a google search. Commented Jul 8, 2015 at 17:13
  • asp.net/web-api Commented Jul 9, 2015 at 9:18

2 Answers 2

1

You should create a webapi controller and it should contain a method that looks something like this. I am assuming you're using Web Api 2.0 with this example.

[Route("api/plotlist")]
[HttpGet]
public PlotListModel GetPlotList() {
    //Here's where you would instantiate and populate your model
    PlotListModel plotList; 

    /*
     * Once your model is instantiated and populated then you can
     * just return it and the serialization will be done for you
     */

    return plotList;
}

Once you have that you can then call that method from your client code using ajax. A simple client function might look something like this if you use jQuery.

function retreivePlotList() {
    $.getJSON("http://<base url>/api/plotlist", function(data) { 
        //do something with data 
    });
}
Sign up to request clarification or add additional context in comments.

15 Comments

Awesome, Casey. Thanks. I will give that a try tonight.
So I’m having an issue. The method is not being called. I’ve put a stop but it’s never been hit.
Can you put the url in your browser and have the method called?
No, I can't. I have localhost/api/plotList and get the 404 error.
Do you have attribute routing configured correctly? Use this tutorial to double check asp.net/web-api/overview/web-api-routing-and-actions/… . Also make sure this method is in an ApiController. The controller should inherit from the ApiController class
|
0

Here’s the web api class

public class PlotListController : ApiController
{
    [Route("api/plotlist")]
    [HttpGet]
    public IEnumerable<CTDIDataPoint> GetPlotList()
    {....

When I put in localhost/api/plotlist I get the 404 error

Here’s the webapiconfig.

public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }

1 Comment

Is this an answer, or were you trying to add clarification to your question.

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.