在剃刀动态匿名类型会导致RuntimeBinderException [英] Dynamic Anonymous type in Razor causes RuntimeBinderException

查看:266
本文介绍了在剃刀动态匿名类型会导致RuntimeBinderException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:

对象不包含RatingName

'object' does not contain a definition for '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());

当然在你的视野:

Of course in your view:

@foreach (var item in Model) {
     <div>x = @item.x, y = @item.y</div>
}

这篇关于在剃刀动态匿名类型会导致RuntimeBinderException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆