0

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&quot;,&quot;string2" ];.

Second, I wrote var list = @JsonConvert.SerializeObject(Model.Elements);, but it rendered: var list = [&quot;string1&quot;,&quot;string2&quot;. In this way, I even tried to parse via JSON.parse() method but I got the error:

Unexpected token & in JSON at position 1

3
  • If you List<string> property is named Elements, then you should create a javascript array using var elements = @Html.Raw(Json.Encode(Model.Elements)) and then you can use var list = elements.join() if you want a comma separated string Commented Jun 8, 2018 at 20:49
  • 1
    @StephenMuecke I'm not sure in this day and age that I'd recommend Json.Encode. I'd probably stick with a Newtonsoft (or other performant and edge-case inclusive serializer) approach. Commented Jun 8, 2018 at 20:51
  • 1
    Thanks for the answers. I didn't find a question about it, so I posted this question. I tested with the Newtonsoft method JsonConvert.SerializeObject() instead of Json.Encode() and it worked perfectly. Commented Jun 8, 2018 at 21:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.