0

I were using a List<> iterating some collection I have in my ASP.NET MVC Model. This is the View:

@for (int i = 0; i < Model.Accessories.Count; i++)
{
    @Html.EditorFor(model => model.Accessories[i])
}

Which iterate this template:

<div class="form-group">
    @Html.Label(Model.Description, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-6 checkbox">
        @Html.HiddenFor(m => m.Id)
        @Html.HiddenFor(m => m.Name)
        @Html.HiddenFor(m => m.RegistrationId)
        @Html.HiddenFor(m => m.Description)
        @Html.EditorFor(m => m.Enabled)
    </div>
</div>

Having this m.Enabled Hint template:

@(Html.Kendo().RadioButtonFor(m => m).Label("Yes").Value(true).HtmlAttributes(new { @class = "rb-observable" }))
@(Html.Kendo().RadioButtonFor(m => m).Label("No").Value(false).HtmlAttributes(new { @class = "rb-observable" }))    

The problem! For some reason, I've needed to change the Accessories collection type from:

Accessories = new List<Accessories>();

To:

Accessories = new HashSet<Accessories>();

(Due to how EntityFramework natively treat tables; it uses HashSet instead of List). Now, I can't use @Html.EditorFor(model => model.Accessories[i]), since its not indexable. And now the View mess the whole radio buttons/id/naming for the inputs.

How can I fix/translate it?

markzzz
  • 47,390
  • 120
  • 299
  • 507

1 Answers1

1

The EditorFor() methods accepts IEnumerable<T> as the model and correctly generates the correct html for each item it the collection based on the EditorTemplate.

Do not generate the html within a loop. It simply needs to be

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

Having said that, it should be irrelevant that you data model collection is HashSet. Your editing data so you should always be using view model, not your data model - refer What is ViewModel in MVC?.