Niels Robin Aagaard
Niels Robin Aagaard

Reputation: 226

Linq call using anonymous/dynamic type does work in view

For the life of me I cannot figure out why this works. I'm simply calling some data via link and passing it on to the view. It works when I passe the data directly like this:

var invoices = (
  from s in navdb.Sales_Invoice_Header
  where s.Salesperson_Code == repCode
  where s.Posting_Date > date
  select s
).ToList();

But when I create an anonymous type on the fly it does not, like this:

var invoices = (
  from s in navdb.Sales_Invoice_Header
  where s.Salesperson_Code == repCode
  where s.Posting_Date > date
  select new { 
    s.No_,
    s.Bill_to_Customer_No_,
    s.Bill_to_Name,
    s.Salesperson_Code
  }
).ToList();

when accessing it like this after:

<table>
@foreach (var invoice in ViewBag.invoices)
{ 
<tr>
    <td>@invoice.No_</td>
    <td>@invoice.Bill_to_Customer_No_</td>
    <td>@invoice.Bill_to_Name</td>
    <td>@invoice.Salesperson_Code</td>
</tr>
}
</table>

I just get an: 'object' does not contain a definition for 'No_'

I've tried adding No_ = s.No_ and so forth, that does not help either. What am I doing wrong?

Upvotes: 2

Views: 122

Answers (2)

GHP
GHP

Reputation: 3231

Duplicate question here: Dynamic Anonymous type in Razor causes RuntimeBinderException

The reason for this is that the anonymous type being passed in the controller in internal, so it can only be accessed from within the assembly in which it’s declared. Since views get compiled separately, the dynamic binder complains that it can’t go over that assembly boundary.

Basically, you can't bind against anonymous dynamic objects in this way. Define a specific class or struct to get around this.

Upvotes: 1

Stephen
Stephen

Reputation: 2047

In your first example, you're getting a List<whatever s is>, in your second example, you're getting a List<object>. And 'object' does not contain a definition for 'No_'

Upvotes: 0

Related Questions