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.
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.
Share Improve this question edited Jul 10, 2013 at 22:33 coredump asked Jul 10, 2013 at 22:22 coredumpcoredump 3,1077 gold badges37 silver badges56 bronze badges3 Answers
Reset to default 8It'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>
Perhaps:
@{
ViewBag.foo = new string[] { "a", "b", "c" };
}
var newFoo = @Html.Raw(Json.Encode(@ViewBag.foo));
Controller
public ActionResult Index()
{
int[] myArray = new int[] { 1, 3, 5, 7, 9 };
ViewBag.myArray = myArray;
return View();
}
View
@{
ViewBag.Title = "Index";
var myArray = (int[])ViewBag.myArray;
var myjsstring = "";
for(int i =0;i<myArray.Length;i++)
{
myjsstring += "mycars[" + i.ToString() + "] = " + myArray[i] + ";";
}
}
<script type="text/javascript">
var mycars = new Array();
@myjsstring
</script>