Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 849
zanona Avatar asked Sep 10 '09 13:09

zanona


People also ask

How pass data from model to view in ASP NET MVC?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

How do I pass ViewData to view?

To pass the strongly-typed data from Controller to View using ViewData, we have to make a model class then populate its properties with some data and then pass that data to ViewData dictionary as Value and selecting Key's name is the programmer's choice.

Can we pass TempData from controller to view?

TempData is used to transfer data from view to controller, controller to view, or from one action method to another action method of the same or a different controller. TempData stores the data temporarily and automatically removes it after retrieving a value. TempData is a property in the ControllerBase class.

How do I pass model list from controller view?

You can use for this: 1 - Using View() , 2 - Using ViewData , 3 - Using ViewBag , 4 - Using your custom class , and 5 - Some combinations of those approaches.


2 Answers

You need to cast in the View

<% var myArray = (string[])ViewData["passedArray"]; %>
like image 70
Daniel Elliott Avatar answered Oct 20 '22 00:10

Daniel Elliott


This should work by casting ViewData["passedArray"] within the view to string[]. Alternatively, if you want to go the extra mile: create a ViewModel class that contains this array as a member and pass that ViewModel to a strongly-typed version of your view.

like image 34
David Andres Avatar answered Oct 20 '22 00:10

David Andres