Inserting multiple entities into many-to-many linking table

梦想的初衷 提交于 2019-11-29 18:15:33

You need to make your StationTimetables property IList and use the indexer so that the properties are correctly named and can be bound on post back

@for (var i = 0; i < 10; i++)
{
  <tr>
    <td>@Html.DropDownListFor(m => m.StationTimetables[i].StationId, Model.StationList, "---", htmlAttributes: new { @class = "form-control col-md-2" })</td>
    <td>@Html.EditorFor(m => m.StationTimetables[i].Arrival, new { htmlAttributes = new { @class = "form-control" } })</td>
    <td>@Html.EditorFor(m => m.StationTimetables[i].Departure, new { htmlAttributes = new { @class = "form-control" } })</td>
  </tr>
}

This will generate the correct name attributes for example

<input name="StationTimetables[0].StationId" ...>
<input name="StationTimetables[1].StationId" ...>

If you cant change it from IEnumerable, you can create a custom EditorTemplate for typeof StationTimetable

Views/Shared/EditorTemplates/StationTimetable.cshtml

@model YourAssembly.StationTimetable
<tr>
  <td>@Html.DropDownListFor(m => m.StationId, (SelectList)ViewData["StationList"], "---", new { @class = "form-control col-md-2" })</td>
  <td>@Html.EditorFor(m => m.Arrival, new { htmlAttributes = new { @class = "form-control" } })</td>
  <td>@Html.EditorFor(m => m.Departure, new { htmlAttributes = new { @class = "form-control" } })</td>
</tr>

and then in the main view

@EditorFor(m => m.StationTimetables, new { StationList = Model.Model.StationList })

This approach means you need to initialize the StationTimetables property with 10 items in the controller before you pass the model to the view.

In any case, I recommend the EditorFor() approach in your case because of a bug (reported but not yet solved) in using DropDownListFor() in a for loop.

However I suspect you don't really always have exactly 10 station timetables (I'm letting the user insert up to 10) which makes this approach inflexible - for example if you add validation attributes to the properties, the model will be invalid unless all 10 time table properties are filled in. It would be better to use javascript or the BeginCollectionItem helper to dynamically add a new timetable. A example of both approaches is included in this answer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!