如何在 ASP.NET MVC 部分视图中使用匿名列表作为模型?
我有一个 Contact
对象列表,我只需要其中的一个属性子集。因此,我使用 LINQ 投影创建一个匿名列表,并将其传递给部分视图。但是当我在部分视图中使用该列表时,编译器说它没有这些属性。我尝试了如下最简单的情况,但仍然没有机会在部分视图中使用匿名对象或列表。
var model = new { FirstName = "Saeed", LastName = "Neamati" };
return PartialView(model);
在部分视图中,我有:
<h1>Your name is @Model.FirstName @Model.LastName<h1>
但它说 @Model 没有 FirstName 和 LastName 属性。这是怎么回事?当我使用 @Model 时,该字符串将在浏览器中呈现:
{ Title = "Saeed" }
I have a list of Contact
objects, from which, I just want a subset of attributes. So I used LINQ projection to create an anonymous list and I passed that to a partial view. But when I use that list in partial view, compiler says that it doesn't have those attributes. I tried the simplest case as follow, but still I have no chance to use an anonymous object or list in a partial view.
var model = new { FirstName = "Saeed", LastName = "Neamati" };
return PartialView(model);
And inside partial view, I have:
<h1>Your name is @Model.FirstName @Model.LastName<h1>
But it says that @Model doesn't have FirstName and LastName properties. What's wrong here? When I use @Model, this string would render in browser:
{ Title = "Saeed" }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要这样做。不要将匿名对象传递给您的视图。它们的属性是内部的,在其他程序集中不可见。视图由 ASP.NET 运行时动态编译成单独的动态程序集。因此,定义视图模型并强类型化您的视图。像这样:
然后:
在你看来:
Don't do this. Don't pass anonymous objects to your views. Their properties are internal and not visible in other assemblies. Views are dynamically compiled into separate dynamic assemblies by the ASP.NET runtime. So define view models and strongly type your views. Like this:
and then:
and in your view:
使用反射来获取值,性能有点慢,但不需要创建不必要的模型
下一个类添加到您的应用程序
在您的视图中将
使用下一个代码希望有帮助
Use Reflection to get the values, preformance a bit slower, but no need ot create unnesasry models
Add next class to your application
in your view use next code
Hope that helps