admin管理员组

文章数量:1243198

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

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

Share Improve this question asked Jul 22, 2015 at 19:29 GlobalJimGlobalJim 1,1992 gold badges17 silver badges24 bronze badges 3
  • Possible duplicate. Have you seen this stackoverflow./questions/6192950/… – Matt Commented Jul 22, 2015 at 19:32
  • Return json from your controller then $.getJSON() on the client – brroshan Commented Jul 22, 2015 at 19:34
  • Why does List<> require this but say a ViewBag with a string does not? – GlobalJim Commented Jul 22, 2015 at 19:40
Add a ment  | 

1 Answer 1

Reset to default 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 bination 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)';

本文标签: cHow to assign a Listltstringgt to a ViewBag and use in JavaScriptStack Overflow