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?
There is a really good library called Json.Net you can use to serialize a .Net objects into Json:
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()))
}
]
}
Pass it as JSON. That's the best way to do it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.