最近做项目是遇到一个问题,在我们的view中经常遇到一些匿名类型对象,然后在通过RenderPartial输出这些对象。
还是举个例子吧,有3个view Index.cshtml、Test.cshtml、Test2.cshtml
它们的层次结构如图:
它们的代码如下:
Index.cshtml
[csharp]
@{
Layout = null;
var obj = new[] {
new {name=“majiang”,age=27},
new {name=“luyang”,age=26}
};
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
@{
<h2>@(obj.GetType()。Assembly.Location)</h2>
Html.RenderPartial(“Test”, obj);
Html.RenderPartial(“Test2”, obj);
}
</div>
</body>
</html>
@{
Layout = null;
var obj = new[] {
new {name=“majiang”,age=27},
new {name=“luyang”,age=26}
};
}
<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
@{
<h2>@(obj.GetType()。Assembly.Location)</h2>
Html.RenderPartial(“Test”, obj);
Html.RenderPartial(“Test2”, obj);
}
</div>
</body>
</html>
Test.cshtml 和Test2.cshtml
[csharp] view plaincopyprint?@{
Layout = null;
var obj = this.Model;
var a = new {name=“majiang”,age=27};
<h2>@(a.GetType()。Assembly.Location)</h2>
foreach (var item in obj)
{
<h3>@item.name</h3>
<h3>@item.age</h3>
}
}
@{
Layout = null;
var obj = this.Model;
var a = new {name=“majiang”,age=27};
<h2>@(a.GetType()。Assembly.Location)</h2>
foreach (var item in obj)
{
<h3>@item.name</h3>
<h3>@item.age</h3>
}
}
发表回复