3

I have a page containing a list of items. Each item in the list has the same list of checkboxes.

However in the rendered page each checkbox for a particular option has the same ID.

How can I ensure that each checkbox is linked back to the parent item?

The view includes this:

@foreach (var item in Model.MyItems)
{
    @Html.DisplayFor(modelItem => item.Name)
    @Html.EditorFor(modelItem => item.Options)
}

I have a template in EditorTemplates like:

@model SelectedOption

@Html.HiddenFor(model => model.OptionId)
@Html.LabelFor(model => model.IsSelected, Model.Description)
@Html.EditorFor(model => model.IsSelected)

My item class includes:

public ICollection<SelectedOption> Options { get; set; } = new HashSet<SelectedOption>();

The SelectedOption class is:

public class SelectedOption
{
    public int OptionId { get; set; }
    public string Description { get; set; }
    public bool IsSelected { get; set; }
}

EDIT

Whilst the linked duplicate question does contain the answer, it wasn't immediately clear to me that it did. So here's what it means for this specific case:

1) Change the view to replace the foreach with an EditorFor():

@Html.EditorFor(model => model.MyItems)

2) Create a new editor template containing the contents of the previous foreach:

@model MyItemType

@Html.DisplayFor(model => model.Name)
@Html.EditorFor(model => model.Options)
Dan
  • 7,446
  • 6
  • 32
  • 46
  • does this approximate what you're referring to? http://stackoverflow.com/questions/21322639/asp-net-mvc-razor-foreach-loop-adding-id-to-div – Wim Ombelets Feb 17 '17 at 12:03

0 Answers0