我很抱歉,如果我第n次问同样的事情,但我找不到我的问题的答案......
我在添加部分视图时遇到问题......
我在数据库表中有一对多的关系。
我的模特是:
using System;
using System.Collections.Generic;
public partial class Job
{
public Job()
{
this.Flights = new HashSet<Flight>();
}
public int JobID { get; set; }
public string JobNumber { get; set; }
public int ClientID { get; set; }
public virtual Client Client { get; set; }
public virtual ICollection<Flight> Flights { get; set; }
}
我的控制器(创建):
// GET: /Jobs/Create
public ActionResult Create()
{
ViewBag.ClientID = new SelectList(db.Clients, "ClientID", "ClientName");
return View();
}
和视图(用于创建作业):
@model AOG.Models.Job
<div class="form-horizontal">
<h4>Job</h4>
<hr />
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.JobNumber, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.JobNumber)
@Html.ValidationMessageFor(model => model.JobNumber)
</div>
</div>
<div class="form-group">
@Html.LabelFor(model => model.ClientID, "ClientID", new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ClientID", String.Empty)
@Html.ValidationMessageFor(model => model.ClientID)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
现在,如果我在创建工作页面上添加部分视图(生成的部分列表视图):
@html.Partial("_PartialFlights");
我收到错误:对象引用未设置为
上的对象实例Line 23: @foreach (var item in Model) {
在我的部分视图中。这是代码:
@model IEnumerable<AOG.Models.Flight>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.FlightName)
</th>
<th>
@Html.DisplayNameFor(model => model.FlightETD)
</th>
<th>
@Html.DisplayNameFor(model => model.FlightETA)
</th>
<th>
@Html.DisplayNameFor(model => model.Job.JobNumber)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.FlightName)
</td>
<td>
@Html.DisplayFor(modelItem => item.FlightETD)
</td>
<td>
@Html.DisplayFor(modelItem => item.FlightETA)
</td>
<td>
@Html.DisplayFor(modelItem => item.Job.JobNumber)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.FlightID }) |
@Html.ActionLink("Details", "Details", new { id=item.FlightID }) |
@Html.ActionLink("Delete", "Delete", new { id=item.FlightID })
</td>
</tr>}</table>
如果我把它放在详细信息视图中:
@foreach (var item in Model.Flights)
{
<div>
<table>
<tr><th>Flight</th><th>ETD</th><th>ETA</th></tr>
<tr>
<td>@Html.DisplayFor(modelItem => item.FlightName)</td>
<td>@Html.DisplayFor(modelItem => item.FlightETD)</td>
<td>@Html.DisplayFor(modelItem => item.FlightETA)</td>
</tr></table>
</div>
}
它显示了我需要的一切,但我想学习如何使用部分视图。
非常感谢你们!
答案 0 :(得分:0)
您需要将IENumerable<Flight>
实例传递给部分视图,而不是:
@html.Partial("_PartialFlights");
......这样做:
@html.Partial("_PartialFlights", Model.Flights);