将数据插入与有效负载的多对多关系

时间:2015-01-19 22:32:16

标签: c# asp.net-mvc entity-framework many-to-many crud

所以我有这个基本的实体模型:

Entity model

StationsTimetables之间的关系是多对多关系,链接表还有一个有效负载ArrivalDeparture。我正在尝试创建的是一个Create页面,用于插入相关数据的时间表。

到目前为止,我已经创建了以下视图模型:

public class TimetablesCreateViewModel
{
    public Timetable Timetable { get; set; }

    public StationTimetable StationTimetable { get; set; }

    public Station Station { get; set; }

    public SelectList StationList { get; set; }
}

我正在TimetablesController Create这样的行动中使用它:

public ActionResult Create()
{
    TimetablesCreateViewModel model = new TimetablesCreateViewModel
    {
        Timetable = new Timetable(),
        StationList = new SelectList(db.Stations, "Id", "Name")
    };

    return View(model);
}

然后,在我看来,我只是循环10次为站点生成表单输入:

<table class="table">
    <tr>
        <th>Station</th>
        <th>Arrival Time</th>
        <th>Departure Time</th>
    </tr>

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

当我浏览页面时,生成表单并且看起来像我想要的那样,但是当我填充它并提交表单时,我得到以下异常:

  

发生了'System.InvalidOperationException'类型的异常   System.Web.Mvc.dll但未在用户代码中处理

     

其他信息:没有类型的ViewData项   “IEnumerable”,其密钥为“StationTimetable”。

我并不太关心异常,我最关心的是如何在HTML中生成表单。输入元素有很多重复的name属性,实际上我似乎错了。

有人能指出我正确的方向吗?

编辑:我通过在model => model.StationTimetable.StationId调用中指定DropDownListFor来修复了异常,但是当我提交表单时,会创建正确的Timetable条目,但StationTimetables数据会不。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

看,在Controller中,您正在创建一个TimetablesCreateViewModel类型的新对象,然后将其发送到视图。在你看来,你正在绕着究竟是什么?一个对象?如果你想像这样循环,你应该创建一个TimetablesCreateViewModel类型的对象列表,并将其发送到视图。

相关问题