Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating over IEnumerable ViewData in controller mvc 5

Tags:

c#

asp.net-mvc

I am trying to foreach loop over a ViewData["element"] in order to build an array

error reads cannot complitly convert object to string[]

        foreach(var p in (IEnumerable<string>)ViewData["element"] as Array)
        {
            string[] workbookIDsLinks = p;
        }

the vuiewdat is from

ViewData["element"] = names.Cast<XmlNode>().Select(e => e.Attributes["id"].Value);

any help would be awesome

like image 461
Mich Avatar asked Dec 01 '25 18:12

Mich


2 Answers

From MSDN:

if an array is cast to the type Array, the result is an object, not an array

So, you've got an object reference, even though you explicitly asked for an Array!

Rather than store an IEnumerable<string> (or IEnumerable<anything>) in ViewData, just convert to an array or list before you store it, by adding ToList() on the end of your assignment. Then you can more easily deal with it on the other end.

In your case, I'm not sure of the type of names, so I'm not sure what you need to do to turn your results into a list of string.

like image 120
Gary McGill Avatar answered Dec 04 '25 08:12

Gary McGill


  1. Don't use IEnumerable<string> here as it can be lazily executed (you can do search for Deferred execution to learn more) and data source can be invalid at this point (DB connection closed, XML file closed, etc). Instead use ToArray() to materialize your colllection.
  2. There is no point of doing foreach as element is already a collection of elements;

In your controller:

ViewData["element"] = names
    .Cast<XmlNode>()
    .Select(e => e.Attributes["id"].Value)
    .ToArray();

In your view:

var workbookIDsLinks = ViewData["element"] as string[];
like image 44
Kaspars Ozols Avatar answered Dec 04 '25 07:12

Kaspars Ozols