zanona zanona - 2 months ago 7
ASP.NET (C#) Question

ASP.NET MVC - How to pass an Array to the view?

I'm struggling myself here, to find a easy way to pass an array from the controller to the view on ASP.NET MVC framework.

so in my controller I would have something like:

public class HomeController : ApplicationController
{
public ActionResult Index()
{
string[] myArray = { "value01", "value02", "value03"};
ViewData["passedArray"] = myArray;
return View();
}
}


so in my view I would have just a call to ViewData["passedArray"] and run a loop on it.

But apparently the ViewData is being received by the view as System.String, probably because of the declaration on the Array DataType, but unfortunately I don't know how to pass it properly and simply without create millions of code lines.

It would be fantastic if one could help me.

Thanks in advance

Answer

You need to cast in the View

<% var myArray = (string[])ViewData["passedArray"]; %>
Comments