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

前端 未结 6 1653
心在旅途
心在旅途 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:21

    I would recommend you sticking to conventions, i.e. replace:

    @Html.EditorFor(m => m.Authors, "AuthorSelector")
    

    with:

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

    and then rename your ~/Views/Shared/EditorTemplates/AuthorSelector.cshtml to ~/Views/Shared/EditorTemplates/AuthorEntryModel.cshtml and make it strongly typed to a single AuthorEntryModel model and get rid of the loop:

    @model AuthorEntryModel
    @Html.TextBoxFor(o => o.FirstName)
    @Html.TextBoxFor(o => o.LastName)
    

    ASP.NET MVC will automatically render the editor template for all elements of the collection and generate proper names.


    UPDATE:

    After seeing your update here's my response:

    In your main view:

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

    In your editor template:

    @model AuthorEntryModel
    
    @Html.TextBoxFor(o => o.FirstName) @Html.TextBoxFor(o => o.LastName)

    You will notice the absence of script in the template which is perfectly normal. Scripts have nothing to do in markup. They go into separate javascript files. In this file you could use jQuery to do whatever you need to do with your markup. It gives you methods such as .index() that allow you to get the index of the element in the matched selector so that you don't need to write any loops and pollute your markup with things like data-line-index attributes.

提交回复
热议问题