How do I send assign a List<string> to a JavaScript array or enumerable object

Eminem picture Eminem · Sep 12, 2012 · Viewed 17.6k times · Source

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"
  }
}

Answer

Darin Dimitrov picture Darin Dimitrov · Sep 12, 2012
<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>