简体   繁体   中英

How to assign a List<string> to a ViewBag and use in JavaScript?

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 comes back as System.Collections.Generic.List 1[System.String]

Way 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 combination 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)';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM