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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With