ASP.NET MVC 2/.NET 4/Razor - 无法在 ViewModel 成员上使用 Any() 扩展方法
我正在尝试 ASP.NET MVC 3 Preview 1 中的 Razor ViewEngine,但在尝试使用 Any()
扩展方法时遇到了问题。
这是我用来在控制器中设置属性的代码:
ViewModel.Comparisons = DB.Comparisons.Where(c => c.UserID == this.UserID).ToArray();
这是我尝试使用 Any()
的视图中的代码:
@if (!View.Comparisons.Any()) {
<tr>
<td>You haven't not started any comparisons yet. @Html.Action("Start a new comparison?", "create", "compare")</td>
</tr>
}
我收到一个异常:
'System.Array' does not contain a definition for 'Any'
我尝试添加 System.Linq
命名空间添加到 web.config 的 pages\namespaces
部分,并在视图顶部添加 @using System.Linq
行,这两者都没有什么区别。我需要做什么才能访问 LINQ 扩展方法?
更新:看起来这与它是动态对象的属性这一事实有关 - 如果我手动将其转换为 IList
,它就会起作用。
I'm trying out the Razor ViewEngine from ASP.NET MVC 3 Preview 1 and I'm running into an issue trying to using the Any()
extension method.
Here's the code I use to set the property in the controller:
ViewModel.Comparisons = DB.Comparisons.Where(c => c.UserID == this.UserID).ToArray();
Here's the code in the View where I try to use Any()
:
@if (!View.Comparisons.Any()) {
<tr>
<td>You haven't not started any comparisons yet. @Html.Action("Start a new comparison?", "create", "compare")</td>
</tr>
}
I get an exception that says:
'System.Array' does not contain a definition for 'Any'
I've tried adding the System.Linq
namespace to both the pages\namespaces
section of web.config, and adding a @using System.Linq
line at the top of the view, neither of which made a difference. What do I need to do to have access to the LINQ extension methods?
Update: It looks like it has to do with the fact that it's a property of a dynamic object - it works if I manually cast it to IList<T>
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,您无法对声明为动态的值调用扩展方法。在这种情况下,ViewModel 返回动态值,因此编译器不知道类型,因此无法找到对扩展方法的调用。
我建议采用以下方法之一:
使用强类型视图。这样,一旦支持,您还可以在 Visual Studio 中获得完整的 Intellisense。
将值显式转换为 IList,然后调用扩展方法。这样编译器就可以进行正确的映射。
Unfortunately you cannot call extension methods on values that are declared as dynamic. In this case ViewModel returns dynamic values, so the compiler doesn't know the type, so calls to extension methods cannot be found.
I recommend one of the following:
Use a strongly-typed view. This way you will also get full Intellisense in Visual Studio, once that is supported.
Cast the values to IList explicitly and then call the extension method. This way the compiler can do the right mapping.
这似乎是动态视图属性的一个错误。如果您将
@if
语句更改为类似的内容,您会发现它有效。
It appears to be a bug with the dynamic View property. If you change your
@if
statement to something likeYou'll see that it works.