在 aspx 页面中使用 C# Dynamic 和嵌入代码
在我后面的代码中,我有一个 public IEnumerable
由 {Transaction, String}
(通过 linq-to-sql 创建为新的匿名对象)组成,其中 Transaction
是我的自定义类创建的。
在我的 aspx 页面中,我想执行以下操作
<% foreach (dynamic trans in AllTransactions) { %>
<span><%= trans.transaction.Amount %></span>
<% } %>
在我后面的代码中,我可以引用 foreach
内的 trans.transaction.Amount
但我似乎没有任何在 aspx 页面上运气好。我得到一个例外:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException:“对象”不包含“事务”的定义
同时,如果我运行调试器,我可以查看“trans”,我看到它内部有一个名为“transaction”的 Transaction 对象交易',它也有我的字符串。此外,其中的“交易”对象包含金额值。看来微软正在某个地方将我的动态转换为对象。
我做的另一项测试是用 GetType() 吐出 trans 的类型是什么,并得到以下结果:
<>f__AnonymousTypef`2[ProjectName.Packages.Investment.Business.Transaction,System.String]
这不是一个常规的“对象”,所以我不确定它的类型是什么。关于为什么我的 foreach 不起作用以及我可以做些什么不同的想法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试将数据绑定到 转发器控制。它旨在输出列表中项目的 html,并将帮助您将设计与逻辑分开,这通常被认为是比尝试在脚本中动态生成 html 更好的做法。
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.
你能尝试如下吗?
或者可以检查一下自定义类Transaction的定义中是否包含名称为“Transaction”的成员变量?
Can you try this as below?
Or can you check whether the definition of the custom class Transaction includes a member variable whose name is "Transaction"?