开发者

Using c# dynamic with embedded code in an aspx page

开发者 https://www.devze.com 2023-02-13 01:41 出处:网络
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 Transactio

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"?

0

精彩评论

暂无评论...
验证码 换一张
取 消