문제

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. 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. Parameter name: source

도움이 되었습니까?

해결책

Is my syntax wrong?

Yes, IEnumerable or ICollection do not have indexer: 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.

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

@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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top