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]

3
  • Possible duplicate. Have you seen this stackoverflow.com/questions/6192950/… Commented Jul 22, 2015 at 19:32
  • Return json from your controller then $.getJSON() on the client Commented Jul 22, 2015 at 19:34
  • Why does List<> require this but say a ViewBag with a string does not? Commented Jul 22, 2015 at 19:40

1 Answer 1

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)';
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.