In my code behind I have a public IEnumerable<dynamic> AllTransactions{ get; set; }
that is composed of {Transaction, String}
(created via linq-to-sql as a new anonymous object) where Transaction
is a custom class I have created.
In my aspx page I would like to do the following
<% foreach (dynamic trans in AllTransactions) { %>
<span><%= trans.transaction.Amount %></span>
<% } %>
In my code behind I can refer to trans.transaction.Amount
inside a foreach
but I don't seem to have any luck on aspx pages. I get an exception:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'transaction'
At the same time, if I have the debugger running I can look at 'trans' and I see it has a Transaction object inside it called 'transaction' and it has my string as well. Further, the 'transaction' object inside it contains a value for Amount. It seems that Microsoft is somewhere converting my dynamic to an object.
One other test I did was spit out what the type of trans is with GetType() and got this:
<>f__AnonymousTypef`2[ProjectName.Packages.Investment.Business.Transaction,System.String]
This is not a regular 'object', so I'm not sure what the type of this is. Any ideas as to why my foreach doesn't 开发者_开发百科work and what I can do differently?
Try binding your data to a repeater control. It was designed to output html for items in lists, and will help you separate your design from your logic, which is generally considered a much better practice than trying to dynamically generate html in script.
Can you try this as below?
<% foreach (dynamic trans in AllTransactions) { %>
<span><%= trans.Amount %></span>
<% } %>
Or can you check whether the definition of the custom class Transaction includes a member variable whose name is "Transaction"?
精彩评论