[英]Using 'Dynamic' to Assist Anonymous Types
I want the ability to grab an anonymous type from my view, that was established by the corresponding controller. 我希望能够从我的视图中获取匿名类型,这是由相应的控制器建立的。 According to this article , such an ability becomes possible in C# 4.0 with the 'dynamic' keyword.
根据这篇文章 ,使用'dynamic'关键字可以在C#4.0中实现这种能力。 However, when I try to find an actual example I find answers ranging from it kinda ' is possible ' to it kinda ' is not possible .'
然而,当我试图找到一个实际的例子时,我发现它的答案有点“ 可能 ”,有点“ 不可能” 。
In my case, I have a controller creating this: 就我而言,我有一个控制器创建这个:
XElement headings = XElement.Parse(part.TagList);
var items = from heading in headings.Descendants("heading")
select new {
name = heading.Attribute("name").Value,
tags = heading.Attribute("tags").Value,
content = shapeHelper.List() //This is a dynamic object!!!
}; //can I add 'as dynamic;' here????
In short it would be nice if, without a static type, my view could simply reach into the model like this: 简而言之,如果没有静态类型,我的视图可以简单地进入模型,这将是很好的:
@{
//Currently this next line returns an error saying that
//'object' contains no method 'Count'
int foo = Model.items.Count();
//This 'foreach' works.
foreach(dynamic lineItem in Model.items){
//But this does not work. Gives another "'object' has no definition for 'name'"
<p>@lineItem.name</p> }
}
Possible? 可能?
Not sure it's exactly what you're looking for, but you could always use the ViewBag
: 不确定它正是您正在寻找的,但您可以随时使用
ViewBag
:
Controller 调节器
ViewBag.Items = from heading in headings.Descendants("heading")
select new {
name = heading.Attribute("name").Value,
tags = heading.Attribute("tags").Value,
content = shapeHelper.List()
};
View 视图
ViewBag.Items.First().content;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.