IEnumerable in my ViewModel is not displayed with EditorForModel

前端 未结 2 1048
遇见更好的自我
遇见更好的自我 2021-01-22 11:30

ViewModel

[Validator(typeof(ProdutoCategoriaValidator))]
public class ProdutoCategoriaViewModel
{
    [HiddenInput(DisplayValue = false)]
    public Guid ID {          


        
2条回答
  •  鱼传尺愫
    2021-01-22 12:07

    A @foreach loop renders something that looks right, but the resulting markup will have the same id for each row's controls. It also will not post the enumerable collection back with the model instance.

    There are two ways to make this work such that you have a unique id for each item in the collection, and so that the collection is hydrated on postbacks:

    1. Use the default editor template rather than a named one

    // editor name parameter must be omitted; default editor template's model type
    // should be a single instance of the child object, not an IEnumerable. This 
    // convention looks wrong, but it fully works:
    @Html.EditorFor(parentObject => parentObject.Items) 
    

    2. Use a @for loop, not a @foreach:

    @for (int i = 0; i < parentObject.Items.Count ; i++) {
        // the model binder uses the indexer to disambiguate the collection items' controls: 
        @Html.EditorFor(c => Model.Items[i], "MyEditorTemplate") 
    }
    

    This will not work, however:

    // this will error out; the model type will not match the view's at runtime:
    @Html.EditorFor(parentObject => parentObject.Items, "MyEditorTemplate")
    

    Nor will this:

    @foreach(var item in parentObject.Items) {
        // this will render, but won't post the collection items back with the model instance: 
        @Html.EditorFor(c => item, "MyEditorTemplate") 
    }
    

    For a detailed answer why this is, look at this question: MVC can't override EditorTemplate name when used in EditorFor for child object.

提交回复
热议问题