1

我是新手,可能遗漏了一些明显的东西。(见下面的代码) Initializer.cs 工作是因为下拉项“Regular”和“Comm”在运行 Create.cshtml 时正确显示。但是,Create.cshtml 不起作用:下拉字段保持空白,而标量字段正确加载。

我花了几个小时查看这个论坛(和其他论坛)的回复,并尝试了无数建议,但都无济于事。例如,有几个人说问题是在控制器和下拉列表中使用相同的名称。我已经进行了更改,但 Create.cshtml 仍然无法正常工作。这是代码:

Models.Flight.cs
public virtual ICollection<FlightType> FlightTypes { get; set; }

Models.FlightType.cs
public class FlightType
{
[Key] 
public int FlightTypeID { get; set; }
public string FlightTypeEntry { get; set; }
}

DAL.FlightInitializer.cs
var flighttypes = new List<FlightType>
{
new FlightType { FlightTypeID = 1, FlightTypeEntry = "Regular" },
new FlightType { FlightTypeID = 2, FlightTypeEntry = "Comm" }
};
flighttypes.ForEach(e => context.FlightType.Add(e));
context.SaveChanges();

Controllers.FlightController.cs
// GET: /Flight/Create
public ActionResult Create()
{
ViewBag.FlightTypeVB = new SelectList(db.FlightType, "FlightTypeID", "FlightTypeEntry");
return View();
}

// POST: /Flight/Create
[HttpPost]
public ActionResult Create(Flight flight)
{
if (ModelState.IsValid)
{
db.Flight.Add(flight);
db.SaveChanges();
return RedirectToAction("Index");
}

ViewBag.FlightTypeVB = new SelectList(db.FlightType, "FlightTypeID", "FlightTypeEntry");
return View(flight);

Views.Flight.Create.cshtml
<div class="editor-label">
@Html.LabelFor(model=>model.AircraftModels)
</div>
<div class="editor-field">
@Html.DropDownList("AircraftModelID", (IEnumerable<SelectListItem>)ViewBag.AircraftModelVB)
@Html.ValidationMessageFor(model => model.AircraftModels)
</div>

非常感谢您的任何建议。

4

0 回答 0