Inserting multiple entities into many-to-many linking table

后端 未结 1 1347
Happy的楠姐
Happy的楠姐 2020-12-22 14:34

My web application has a many-to-many link between the Station and Timetable entities, and the entity that links them is called StationTimeta

相关标签:
1条回答
  • 2020-12-22 14:45

    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

    0 讨论(0)
提交回复
热议问题