本文介绍了Razor 中的动态匿名类型导致 RuntimeBinderException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到以下错误:
'object' 不包含 'RatingName' 的定义
当您查看匿名动态类型时,它显然具有 RatingName.
When you look at the anonymous dynamic type, it clearly does have RatingName.
我意识到我可以用元组来做到这一点,但我想了解为什么会出现错误消息.
I realize I can do this with a Tuple, but I would like to understand why the error message occurs.
推荐答案
在我看来,具有内部属性的匿名类型是一个糟糕的 .NET 框架设计决策.
Anonymous types having internal properties is a poor .NET framework design decision, in my opinion.
这是一个快速且不错的扩展来解决这个问题,即将匿名对象立即转换为 ExpandoObject.
Here is a quick and nice extension to fix this problem i.e. by converting the anonymous object into an ExpandoObject right away.
public static ExpandoObject ToExpando(this object anonymousObject)
{
IDictionary<string, object> anonymousDictionary = new RouteValueDictionary(anonymousObject);
IDictionary<string, object> expando = new ExpandoObject();
foreach (var item in anonymousDictionary)
expando.Add(item);
return (ExpandoObject)expando;
}
使用起来非常简单:
return View("ViewName", someLinq.Select(new { x=1, y=2}.ToExpando());
当然在您看来:
@foreach (var item in Model) {
<div>x = @item.x, y = @item.y</div>
}
这篇关于Razor 中的动态匿名类型导致 RuntimeBinderException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!