ASP NET MVC array in controller to client side array

26,599

Solution 1

It's easy to "render" an array to a Javascript object, using string.Join or similar:

@{
    ViewBag.a = new int[] { 1, 2, 3 };
    ViewBag.b = new string[] { "a", "b", };
}

<script type='text/javascript'>
    // number array
    var a = [ @(string.Join(", ", (int[])ViewBag.a)) ];
    console.log(a);  // [1, 2, 3]

    // string array -- use Html.Raw
    var b = [@Html.Raw("'" + string.Join("', '", (string[])ViewBag.b) + "'")];
    console.log(b);
</script>

Solution 2

Perhaps:

@{
    ViewBag.foo = new string[] { "a", "b", "c" };
}

var newFoo = @Html.Raw(Json.Encode(@ViewBag.foo));
Share:
26,599
coredump
Author by

coredump

Updated on December 06, 2020

Comments

  • coredump
    coredump over 3 years

    My question is how ( if possible ) from an array like string[] a; that I pass it to the view through the ViewBag, how can I obtain a javascript array of strings.

    I want to use this because I get a set of data from the DB and I want in the view to make chart and for that I need a javascript array.