when passing a collection to EditorFor(), it generates invalid names for input elements

前端 未结 6 1693
心在旅途
心在旅途 2021-02-06 02:06

I have a BookCreateModel which consists of book\'s plane info such as Title, PublishYear & etc plus a collection of book Authors (complex type) :

public clas         


        
6条回答
  •  生来不讨喜
    2021-02-06 02:28

    I stumbled upon this when I was trying to find the solution for pretty much the same issue. My workaround was to kick the can down the road, ie. make wrapper model for the collection and use that in the editor template. In provided case, it would be:

    public class BookCreateModel
    {
        public string Title { get; set; }
        public int Year { get; set; }
        public BookAuthorsModel Authors { get; set; }
    }
    
    public class BookAuthorsModel
    {
        IList Items { get; set; }
    }
    

    Then rename your editor template to "BookAuthorsModel.cshtml" and make it like this:

    @model BookAuthorsModel
    
    @for (int i = 0; i < Model.Items.Count; i++) {
    @Html.TextBoxFor(o => Items.o[i].FirstName) @Html.TextBoxFor(o => Items.o[i].LastName)
    }

    And when you want to use it, simply call:

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

    It should then generate input fields like so:

    
    
    

    In my case I also changed Automapper mapping settings appropriately Controller code. This is not usable for some more complex scenarios however and is thus probably just a workaround.

提交回复
热议问题