简体   繁体   English

模型绑定到列表EditorFor编译错误

[英]Model binding to a list EditorFor compilation error

What I'm trying to do here appears to be pretty common, but I can't run this code. 我在这里尝试做的似乎很常见,但我无法运行此代码。 I get a compilation error. 我收到编译错误。

I'm trying to bind to an ienumerable or icollection in a viewmodel. 我正在尝试绑定到viewmodel中的可映射或icollection。 Is my syntax wrong? 我的语法错了吗? Is there a new way of doing thing I missed. 是否有一种新方法可以做我错过的事情。

@for(var i=0; i < Model.traces.Count(); ++i)
{
    @Html.EditorFor(x => x.traces[i].status)
}

The details of my architecture are at a previous post of mine that led to this... 我的架构的细节在我之前的帖子中导致了这个......

Getting error on POST with Entity Framework - Value cannot be null. 使用Entity Framework在POST上获取错误 - 值不能为null。 Parameter name: source 参数名称:source

Is my syntax wrong? 我的语法错了吗?

Yes, IEnumerable or ICollection do not have indexer: x.traces[i] . 是的,IEnumerable或ICollection没有索引器: x.traces[i]

It would be better if you used a collection whose elements can be accessed by index such as IList<T> or T[] , depending on the concrete type of your view model. 如果您使用了一个集合,其元素可以通过IList<T>T[]等索引访问,那将会更好,具体取决于视图模型的具体类型。

Then you will be able to do this: 然后你就可以这样做:

@model IList<MyViewModel>
...
@for (var i = 0; i < Model.traces.Count; i++)
{
    @Html.EditorFor(x => x.traces[i].status)
}

The framework is quite smart in this case, if you have made your own EditorTemplate for the model Trace , you can actually just write 在这种情况下,框架非常智能,如果您为模型Trace了自己的EditorTemplate,您实际上可以只编写

@Html.EditorFor(m => m.traces)

and MVC will render an editor for each item in the list and give you the right fieldnames for each index. MVC将为列表中的每个项目呈现一个编辑器,并为每个索引提供正确的字段名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM