0

Why is this Html Helper code so nasty? I specify the ID to bind to in the linq expression, but have to do it again in the SelectList? Is there a better way to do this but still keep RelationshipTypes as an IEnumerable?

Model:

public class ResponderGuestsModel
{
    public List<GuestInfo> Guests { get; set; }
    public IEnumerable<Business.RelationshipType> RelationshipTypes { get; set; }

        public class GuestInfo
        {
            public int? RelationshipTypeId { get; set; }
        }
    }
}

View:

@for (int i = 0; i < Model.Guests.Count; i++)
{
    @Html.DropDownListFor(model => model.Guests[i].RelationshipTypeId, new SelectList(Model.RelationshipTypes, "RelationshipTypeId", "Name", Model.Guests[i].RelationshipTypeId), "", new { @class = "form-control" })
}
Micah B.
  • 1,097
  • 4
  • 13
  • 27
  • Must you use the selectedvalue parameter? It may still automatically bind if you leave it out. – moarboilerplate Nov 25 '15 at 17:37
  • Possible duplicate of: http://stackoverflow.com/questions/8505264/html-dropdownlistfor-with-custom-parameter – Siva Gopal Nov 25 '15 at 18:15
  • This is a well known limitation of using `DropDownListFor()` in a loop. If you want to avoid creating a new `SelectList` in each iteration, then you need an `EditorTemplate for typeof `GuestInfo` and pass the `SelectList` to it using additional ViewData –  Nov 26 '15 at 02:56

0 Answers0