Search code examples
asp.net-mvcrazorhtml-listshtml-helperbegincollectionitem

MVC BeginCollectionItem Hidden index <li>


I am using BeginCollectionItem HTMLHelper. It works as a charm but it messes up the layout I'm using. BeginCollectionItem renders a <ul> and <li> to hide it's hidden fields (which contains the unique indexes). So each 'row' you have in your collection will generate a <li>.

When you populate your table with BeginCollectionItem it generates the following above the <table>.

<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>

The question: I don't want those <li> and <ul> to be visible as the content of those are 'hidden fields' anyway. How can I achieve this?

Thanks for the help,


Solution

  • You simply need to edit the template file which is called Collection.cshtml and resides in the Views/Shared/EditorTemplates folder in your project.

    By default it looks like this:

    @using HtmlHelpers.BeginCollectionItem
    
    <ul>                                 
        @foreach (object item in Model)
        {
            <li>
                @using (Html.BeginCollectionItem(Html.ViewData.TemplateInfo.HtmlFieldPrefix))
                {
                    @Html.EditorFor(_ => item, null, "")
                }
            </li>
        }
    </ul>
    

    So just edit it to suit your needs (perhaps simply removing the ul and li tags.