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
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.
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.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[];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With