I’m using Razor to insert items into a Javascript array. It’s working as intended using the code below. However, it results in one extra comma at the end of the array. Can someone suggest a way to prevent this from happening?
graphByMonth = new Array(
@foreach (var cost in Model.Cost) {
<text>
[@cost.CPM, '@cost.EndDate'],
</text>
}
);
You should never use any string concatenations when dealing with javascript. If you want to pass some server side model to a javascript variable you could JSON serialize it like this to ensure that dangerous characters are properly escaped:
which will render as:
Using
Json.Encodeyou ensure that the values are properly encoded and you won’t have any broken syntax which is what you will get if you ever try to manually do this by using some string concatenations, foreach loops or whatever.