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

I am creating and assigning values ​​to a list of strings in my controller. I want to assign a 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 it fruitList

returns asSystem.Collections.Generic.List 1[System.String]

+3


source to share


1 answer


Method 1:

You can use Html.Raw()

, and Json.Encode

for him:

var fruitList = @Html.Raw(Json.Encode(ViewBag.FruitList));

      

Method 2:

you can use Json.Parse()

in combination with Html.Raw()

to parse the original string into json:



var fruitList = JSON.parse('@Html.Raw(ViewBag.FruitList)');

      

Method 3:

you can also use the class JsonConvert

using NewtonSoft JSON to serialize it to json:

var fruitList = '@JsonConvert.Serialize(ViewBag.FruitList)';

      

+10


source







All Articles