5

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]

GlobalJim
  • 1,149
  • 2
  • 16
  • 24

1 Answers1

14

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)';
Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160