Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 997
GlobalJim Avatar asked Jul 22 '15 19:07

GlobalJim


1 Answers

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)';
like image 173
Ehsan Sajjad Avatar answered Oct 24 '22 17:10

Ehsan Sajjad