Reputation: 1189
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]
Upvotes: 5
Views: 10949
Reputation: 62488
You can use Html.Raw()
and Json.Encode
for it:
var fruitList = @Html.Raw(Json.Encode(ViewBag.FruitList));
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)');
you can also use JsonConvert
class using NewtonSoft JSON to serialize it to json:
var fruitList = '@JsonConvert.Serialize(ViewBag.FruitList)';
Upvotes: 14