简体   繁体   中英

Asp.Net MVC EditorFor Array with template

I have a model of ClassA that has a property that is an array of ClassB.

public class ClassA
{
    public string ClassAProperty1 { get; set; }
    public string ClassAProperty2 { get; set; }
    public ClassB[] MySubCollection { get; set; }
}

public class ClassB
{
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
}

I'd like to edit my instances of ClassB in a table. I've created an EditorTemplate for ClassB that creates a table row.

    @model ClassB
    <tr>
        <td>@Html.TextBoxFor(m => m.Prop1)</td>
        <td>@Html.TextBoxFor(m => m.Prop2)</td>
    </tr>

This works great on the edit view for ClassA since MVC does all the field indexing magic itself:

@Html.TextBoxFor(m => m.ClassAProperty1)
@Html.TextBoxFor(m => m.ClassAProperty2)

<table>
    <tr>
        <th>Col</th>
        <th>Col</th>
    </tr>
    @Html.EditorFor(m => m.MySubCollection)
</table>

However, I'd actually like to create an editor template for the array that includes the table tag like this:

@model ClassB[]
<table>
    <tr>
        <th>Col</th>
        <th>Col</th>
    </tr>
   @foreach(var item in Model)
   {
       @Html.EditorFor(m => item)
   }
</table>

So I can simply do:

@Html.TextBoxFor(m => m.ClassAProperty1)
@Html.TextBoxFor(m => m.ClassAProperty2)
@Html.EditorFor(m => m.MySubCollection)

However, the field indexing is not applied with this approach. Is there a way I can accomplish this without having to build the textbox names myself? Being a template, I don't know the property name at the time of use.

I figured it out. Razor is pretty smart. Using a for loop instead of a foreach solves it:

@for (var i = 0; i < Model.Length; i++)
{
    @Html.EditorFor(c => Model[i])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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