我一直在对本网站上讨论的匿名类型使用 ExpandoObject() 解决方法。我遇到了一个问题,因为我的视图无法编译。我使用了以下扩展名:
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;
}
...这使我可以执行以下操作:
控制器:
var latestDiscussions = repository.Messages
.OrderByDescending(m => m.DateCreated)
.GroupBy(m => m.Discussion.DiscussionId)
.Take(10)
.Join(repository.Discussions,
m => m.Key,
d => d.DiscussionId,
(m, d) => new
{
Id = m.Key,
Title = d.Title,
Guid = d.Guid,
UrlTitle = d.UrlTitle,
ViewCount = d.ViewCount
}).ToExpando();
看法:
@foreach (var discussion in Model.Latest)
{
<div>
@Html.RouteLink(discussion.Title, "DisplayDiscussion", new { guid = discussion.Guid, urlTitle = discussion.UrlTitle, action = "Display", controller = "Discussion" })
</div>
}
我的模型如下所示:
public class IndexModel
{
public IQueryable<Discussion> MostPopular { get; set; }
public ExpandoObject Latest { get; set; }
}
但是,我收到一个编译错误,说是讨论。标题:
编译器错误消息:CS1061:“System.Collections.Generic.KeyValuePair”不包含“Title”的定义,并且找不到接受“System.Collections.Generic.KeyValuePair”类型的第一个参数的扩展方法“Title”(您是否缺少 using 指令或程序集引用?)
我错过了什么?
提前致谢!
标记