0

Here is my javascript and below is my C# code:

    //javascript in view
    var data = {
        labels: [@Misc.printData(Model.chartLabels, true)],
        datasets: [
            {
                fillColor: "rgba(151,187,205,0.5)",
                strokeColor: "rgba(151,187,205,1)",
                data: [@Misc.printData(Model.chartData, false)]
            }
        ]
    }

    //C# helper
    public static IHtmlString printData(IEnumerable<string> data, bool putQuotes)
    {
        string str = String.Empty;

        if (!data.Any())
            return new HtmlString(str);

        if (putQuotes)
            str = @"""" + data.Aggregate((result, next) => result + @""", """ + next) + @"""";
        else
            str = data.Aggregate((result, next) => result + ", " + next);

        return new HtmlString(str);
    }

I am trying to populate a data structure in javascript with the information in a C# model passed to me by the controller. This is obviously an awful hack. Is there a better way to do it?

2
  • U can use ViewBag set it works more like sesion variable but with that you can comunicate if you dont work with MVC Commented Mar 21, 2014 at 18:09
  • Have you considered passing it as JSON ? Commented Mar 21, 2014 at 18:10

3 Answers 3

1

Using JSON.NET (available via NuGet), you can do this in your Razor view:

@Html.Raw(Newtonsoft.Json.Linq.JToken.FromObject(Model).ToString()))

That will write out a JSON representation of your Model object. This can of course be encapsulated in a helper function so it's not so hard to read.

To match your example, you would do this:

var data = {
    labels: @Html.Raw(Newtonsoft.Json.Linq.JToken.FromObject(Model.chartLabels).ToString())),
    datasets: [
        {
            fillColor: "rgba(151,187,205,0.5)",
            strokeColor: "rgba(151,187,205,1)",
            data: @Html.Raw(Newtonsoft.Json.Linq.JToken.FromObject(Model.chartData).ToString()))
        }
    ]
}
Sign up to request clarification or add additional context in comments.

2 Comments

Excellent, thank you! I've never used JSON before but you made it very easy.
@sirdank JSON stands for JavaScript Object Notation, so if you've used JS, you've sort of already been using JSON without knowing it.
1

There is a really good library called Json.Net you can use to serialize a .Net objects into Json:

Json.Net

Comments

0

Pass it as JSON. That's the best way to do it.

Comments

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.