I am trying to pass a list of strings from the server-side to be used on client-side. I'm using Razor and ASP.NET MVC.
In other part of my code, I could pass a list of integers. I declared a List<int> and returned inside a model to the view to be rendered. On the view, I could pass to the JavaScript in the following way:
var list = [ @string.Join(",", Model.Elements); ];
There is a way to pass a list of string (List<string>) in a similar way.
Note: I've tried in two ways:
First, I wrote
var list = [ "@string.Join("\",\"" , Model.Elements)" ];, but it rendered: var list = [ "string1","string2" ];.
Second, I wrote var list = @JsonConvert.SerializeObject(Model.Elements);, but it rendered: var list = ["string1","string2". In this way, I even tried to parse via JSON.parse() method but I got the error:
Unexpected token & in JSON at position 1
List<string>property is namedElements, then you should create a javascript array usingvar elements = @Html.Raw(Json.Encode(Model.Elements))and then you can usevar list = elements.join()if you want a comma separated stringJson.Encode. I'd probably stick with a Newtonsoft (or other performant and edge-case inclusive serializer) approach.JsonConvert.SerializeObject()instead ofJson.Encode()and it worked perfectly.