1

I have a string List on server that Im sending to a partial view.

List<string> list = new List<string>();
list.Add("1");
list.Add("2");

On Client Side I'm converting the list to json like this:

var stringList = @(Html.Raw(Json.Encode(this.Model.StringList)));
alert(stringList );

The alert reply is: 1,2 and I should get ["1","2"].

Any clue on how to deal with this?

Thanks a lot.

1
  • 2
    Go to your web browser's console, and enter alert(["1", "2"]). Hit Enter. It will alert 1,2 because ["1", "2"].toString() === "1,2". You should try to console.log(stringList) and see what it really is -- perhaps you already have what you seek. Commented Aug 14, 2012 at 20:03

1 Answer 1

4

What your asking for is a plain and simple array, not json.

That aside, just append brackets around it:

var stringList = [@(Html.Raw(Json.Encode(this.Model.StringList)))];
alert(stringList ); 

This works for numbers but if you intend to use it with real string values (like words or such) you'll need a different approach. It isn't clear if you intent to use this with numbers treated as strings as your example or not.

Sign up to request clarification or add additional context in comments.

2 Comments

I don't see why you're telling him to manually add square brackets. Json.Encode already adds square brackets.
No, in this case Json.Encode outputs a comma separated list of values without the brackets. The brackets would only be output if the object being encoded was something that had a property that was a list of objects. This is an older answer that was created over a year and a half ago, newer versions of MVC may have changes this behavior.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.