mercredi 9 avril 2014

c# - ASP.NET MVC : tableau 2D passant de Controller à l'affichage - Stack Overflow


I have a 2D array in the controller:


 public ActionResult Home()
{
string[][] a = new string[250][];

for (int x = 0; x < a.Length; x++)
{
a[x] = new string[2];
a[x][0] = b[x];
a[x][1] = b[x];
}

return View();
}

where "b" is a 1D array with the same length as "a".


How do I pass the 2D array "a" into the JavaScript in the view?




I suggest you look at the tutorial here as a good introduction to the links between controller, views and models.




Found the answer myself through trial and error. Seems like JavaScript can in fact interpret 2D Arrays from C# when serialized through Json.


In controller:


for (int x = 0; x < a.Length; x++)
{
a[x] = new string[2];
a[x][0] = b[x];
a[x][1] = b[x];
}

ViewBag.a = a;

In view:


var a2 =  @Html.Raw(Json.Encode(ViewBag.a));
alert("First value of first term: " + a2[0][0] + "Second value of first term: " + a2[0][1]);


I have a 2D array in the controller:


 public ActionResult Home()
{
string[][] a = new string[250][];

for (int x = 0; x < a.Length; x++)
{
a[x] = new string[2];
a[x][0] = b[x];
a[x][1] = b[x];
}

return View();
}

where "b" is a 1D array with the same length as "a".


How do I pass the 2D array "a" into the JavaScript in the view?



I suggest you look at the tutorial here as a good introduction to the links between controller, views and models.



Found the answer myself through trial and error. Seems like JavaScript can in fact interpret 2D Arrays from C# when serialized through Json.


In controller:


for (int x = 0; x < a.Length; x++)
{
a[x] = new string[2];
a[x][0] = b[x];
a[x][1] = b[x];
}

ViewBag.a = a;

In view:


var a2 =  @Html.Raw(Json.Encode(ViewBag.a));
alert("First value of first term: " + a2[0][0] + "Second value of first term: " + a2[0][1]);

0 commentaires:

Enregistrer un commentaire