12

我有以下内容:

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

现在如何在 JavaScript 端分配ViewBag.SomeEnumerable给一个array或某种形式的可枚举对象?例如:

function SomeFunction()
{
  var array = @ViewBag.SomeEnumerable;
  for(var eachItem in array)
  {
    alert(eachItem); // should display "string1" then string2"
  }
}
4

1 回答 1

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>

将呈现为:

<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>
于 2012-09-12T09:13:03.213 回答