我需要填充表單上設備的複選框列表以供用戶請求設備。列表的數據存儲在名爲「設備」的表格中。我正在使用EF 6數據庫。該視圖是強類型的,並將寫入「訂單」表。我被困在如何使用視圖模型而不是ViewBag來填充表單的複選框列表。我曾看過MikesDotNetting,Rachel Lappel關於視圖模型和其他幾個人的帖子,這對我來說沒有意義。下面
代碼:.NET MVC 5使用視圖模型從數據庫複選框列表
public class Equipment
{
public int Id { get; set; }
public string Description { get; set; }
public string Method { get; set; }
public bool Checked { get; set; }
}
public class Order
{
public int id{ get; set; }
public string Contact_Name { get; set; }
public List<Equipment>Equipments { get; set; }
public string Notes { get; set; }
}
控制器:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Contact_Name,Equipment,Notes")] Order order)
{
if (ModelState.IsValid)
{
db.Orders.Add(order);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(order);
}
查看
@model CheckBoxList.Models.Order
@{
ViewBag.Title = "Create";
}
<h2>Create</h2>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Order</h4>
<hr />
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<div class="form-group">
@Html.LabelFor(model => model.Contact_Name, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Contact_Name, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Contact_Name, "", new { @class = "text-danger" })
</div>
</div>
<div class="form-group">
//checkbox list populated here
</div>
<div class="form-group">
@Html.LabelFor(model => model.Notes, htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.Notes, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Notes, "", new { @class = "text-danger" })
</div>
</div>
我似乎沒有正確填充Model.Equipments,因爲我收到一個NullReferenceException錯誤。我更新了上面的原始代碼。設備列表現在應該是調用設備類而不是查看模型 –