12

I have the following :

ViewBag.SomeEnumerable = new List<string>() { "string1", "string2" };

Now how do I assign ViewBag.SomeEnumerable to an array or some form of enumerable object on the JavaScript side? e.g.:

function SomeFunction()
{
  var array = @ViewBag.SomeEnumerable;
  for(var eachItem in array)
  {
    alert(eachItem); // should display "string1" then string2"
  }
}
abatishchev
  • 98,240
  • 88
  • 296
  • 433
Eminem
  • 7,206
  • 15
  • 53
  • 95

1 Answers1

30
<script type="text/javascript">
function SomeFunction() {
    var array = @Html.Raw(Json.Encode(ViewBag.SomeEnumerable));
    for(var i = 0; i < array.length; i++) {
        alert(array[i]); // should display "string1" then string2"
    }
}
</script>

will be rendered as:

<script type="text/javascript">
function SomeFunction() {
    var array = ["string1","string2"];
    for(var i = 0; i < array.length; i++) {
        alert(array[i]); // should display "string1" then string2"
    }
}
</script>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • VS is giving `syntax error at ;` when i declare var array = @Html.Raw(Json.Encode(ViewBag.SomeEnumerable)); however o/p is correct in html rendered in browser – Ishaan Puniani Apr 22 '13 at 19:59
  • 2
    @IshaanPuniani, why do you even trust VS Intellisense? It is wrong. Look at the rendered markup to see that it is correct despite VS telling you it is wrong. – Darin Dimitrov Apr 22 '13 at 20:42