How to get rid of the comma at the end of this Javascript array filled with Razor?

I use Razor to insert elements into a Javascript array. It works as intended using the code below. However, this results in one extra comma at the end of the array. Can anyone suggest a way to prevent this?

graphByMonth = new Array( @foreach (var cost in Model.Cost) { <text> [@cost.CPM, '@cost.EndDate'], </text> } ); 
+4
source share
1 answer

You should never use string concatenation when working with javascript. If you want to pass some server-side model to a javascript variable, you can JSON serialize it to ensure that dangerous characters are properly escaped:

 var graphByMonth = @Json.Encode(Model.Cost.Select(cost => new { cpm = cost.CPM, endDate = cost.EndDate })); 

which will be displayed as:

 var graphByMonth = [ { cost: '1', endDate: 'date 1' }, { cost: '2', endDate: 'date 2' }, { cost: '3', endDate: 'date 3' } ]; 

Using Json.Encode , you will ensure that the values ​​are correctly encoded, and you will not have any broken syntax that you get if you try to manually do this using some string concatenation, foreach loops or something else.

+2
source

Source: https://habr.com/ru/post/1389015/


All Articles