Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP NET MVC array in controller to client side array

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.

like image 573
coredump Avatar asked Jul 10 '13 22:07

coredump


1 Answers

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>
like image 53
McGarnagle Avatar answered Oct 24 '22 02:10

McGarnagle