最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert List<string> to Json Array on client ASP.NET MVC - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Aug 14, 2012 at 19:56 Derek 朕會功夫 94.5k45 gold badges198 silver badges253 bronze badges asked Aug 14, 2012 at 19:54 VAAAVAAA 15.1k28 gold badges143 silver badges270 bronze badges 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. – Linus Thiel Commented Aug 14, 2012 at 20:03
Add a ment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论