0

I'm writing a small web app that requires I display the properties of a collection of PSObject on an ASP.NET C# Web Page.

In my controller class, a .cs file, I can access the First() method of a collection as such:

Collection<PSObject> test = new Collection<PSObject>();
test.First();

However when I try and do something similar in my .cshtml, trying to enumerate the property names for the table header, I get an exception that this method does not exist.

<tr>
        @{
            if (ViewBag.VIDatastores != null)
            {
                foreach (var prop in ViewBag.VIDatastores.First().Properties)
                {
                    <th>@prop.Name</th>
                }
            }
        }
</tr>

Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'System.Collections.ObjectModel.Collection' does not contain a definition for 'First'

I have also tried simply accessing element 0, as there is a null-check already in place:

foreach (var prop in ViewBag.VIDatastores[0].Properties)

Which returns a different exception:

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Now I of course debugged this, and the Properties property correctly enumerates in the Locals window (it is most absolutely not null).

What a I doing wrong?

The closest matching answer seemed to point to a missing assembly reference in web.config; but since this class is in System.dll (to my knowledge) and it is already referenced properly, I'm not sure what to do.

Daenks
  • 1
  • 1
  • 1
    I'd highly recommend [using view models](http://www.asp.net/mvc/overview/getting-started/introduction/accessing-your-models-data-from-a-controller) instead of the ViewBag (After all the M in MVC stands for model). – Erik Philips Mar 11 '16 at 19:11
  • I'd love to, but AFAIK there is no way to use a PowerShell data-source in Entity Framework without a $700 paid library, and I dont know how to write my own Model that encapsulates it (yet). – Daenks Mar 11 '16 at 19:28
  • 1
    What you just said makes no sense. If you can populate a ViewBag you can populate a model. – Erik Philips Mar 11 '16 at 19:37
  • Ok then, maybe i'm over-complicating something in my grey-matter. Time for more googling. Thanks – Daenks Mar 11 '16 at 19:43

0 Answers0