admin管理员组文章数量:1243198
I create and assign values to a list of strings in my controller. I want to assign the list of values to a JavaScript variable. How can I do this?
Controller:
List<string> fruits = new List<string>();
list.Add('Apple');
list.Add('Banana');
list.Add('Kiwi');
ViewBag.FruitList = fruits;
View:
var fruitList = '@ViewBag.FruitList';
When I run the program fruitList
es back as System.Collections.Generic.List 1[System.String]
I create and assign values to a list of strings in my controller. I want to assign the list of values to a JavaScript variable. How can I do this?
Controller:
List<string> fruits = new List<string>();
list.Add('Apple');
list.Add('Banana');
list.Add('Kiwi');
ViewBag.FruitList = fruits;
View:
var fruitList = '@ViewBag.FruitList';
When I run the program fruitList
es back as System.Collections.Generic.List 1[System.String]
- Possible duplicate. Have you seen this stackoverflow./questions/6192950/… – Matt Commented Jul 22, 2015 at 19:32
-
Return json from your controller then
$.getJSON()
on the client – brroshan Commented Jul 22, 2015 at 19:34 - Why does List<> require this but say a ViewBag with a string does not? – GlobalJim Commented Jul 22, 2015 at 19:40
1 Answer
Reset to default 14Way 1:
You can use Html.Raw()
and Json.Encode
for it:
var fruitList = @Html.Raw(Json.Encode(ViewBag.FruitList));
Way 2:
you can use Json.Parse()
in bination with Html.Raw()
to parse the raw string in to json:
var fruitList = JSON.parse('@Html.Raw(ViewBag.FruitList)');
Way 3:
you can also use JsonConvert
class using NewtonSoft JSON to serialize it to json:
var fruitList = '@JsonConvert.Serialize(ViewBag.FruitList)';
本文标签: cHow to assign a Listltstringgt to a ViewBag and use in JavaScriptStack Overflow
版权声明:本文标题:c# - How to assign a List<string> to a ViewBag and use in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740131084a2229758.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论