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

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

    Here's an extension method you can use which will render a partial view and use the correct HTML field prefix:

    Extension Method

        /// 
        /// Helper method that renders the specified partial view as a HTML-encoded string using the specified
        /// collection as the model, with the intention that the partial view will use an editor template on the items
        /// in the collection.
        /// 
        /// the model type
        /// the property type
        /// the  instance
        /// the name of the partial view to render
        /// the model collection property expression
        /// the HTML-encoded string
        public static MvcHtmlString PartialContainingEditorForCollection
            (this HtmlHelper htmlHelper, string partialViewName,
             Expression> collectionExpression)
            where TProperty : IEnumerable
        {
            var viewData = htmlHelper.ViewContext.ViewData;
            var model = (TModel) viewData.Model;
            var collection = collectionExpression.Compile().Invoke(model);
    
            var htmlFieldPrefix = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(
                ExpressionHelper.GetExpressionText(collectionExpression));
    
            return htmlHelper.Partial(partialViewName, collection,
                                      new ViewDataDictionary
                                          {
                                              TemplateInfo = new TemplateInfo {HtmlFieldPrefix = htmlFieldPrefix}
                                          });
        }
    

    Sample Usage

    @Html.PartialContainingEditorForCollection("_TableWithSummary", m => Model.FormModel.ItemsToOrder)
    

提交回复
热议问题