. net MVC 5使用视图模型从数据库的复选框列表
本文关键字:数据库 复选框 列表 模型 视图 MVC net | 更新日期: 2023-09-27 18:01:54
我需要在表单上填充设备的复选框列表,以便用户请求设备。列表的数据存储在名为"Equipment"的表中。我首先与EF 6数据库一起工作。该视图是强类型的,将写入"Orders"表。我卡住了如何使用视图模型,而不是ViewBag填充表单的复选框列表。我看过mikesdotnettting, Rachel Lappel关于视图模型的帖子和其他几个,对我来说没有意义。
下列代码:
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>
如何将复选框值绑定到整数列表?
该示例使用Guid作为PK,但可以很容易地将其替换为int。
我假设你的Equipment类是你的EF实体。
我们要创建订单页面那么我们从CreateOrderViewModel
开始public class CreateOrderViewModel
{
public string Contact_Name { get; set; }
public Dictionary<int, string> AllEquipment{ get; set; }
public int[] SelectedEquipment { get;set; }
public string Notes { get; set; }
}
填写装备的id和名称。这是显示所有设备复选框所需的设备的完整列表,其中包含设备id的值。
比如
var viewModel = new CreateOrderViewModel {
AllEquipment = context.Equipment.ToDictionary(e => e.Id, e.Description);
}
selecteequipment是选中复选框的设备列表。因此,当你将这些信息发回时,SelectedEquipment属性将有一个需要附加到订单上的所有id的列表。
当您创建订单时,只需遍历列表并将它们添加到订单实体中的设备列表中。
在列表中创建一个for循环,并为其中的每个项目生成一个复选框。
<div class="form-group">
@for (int i = 0; i < Model.Equipments.Count(); i++)
{
@Html.CheckBoxFor(x => x.Equipments[i].Checked)
@Model.Equipments[i].Description
//If you need to hide any values and get them in your post
@Html.HiddenFor(x => x.Equipments[i].Id)
@Html.HiddenFor(x => x.Equipments[i].Method)
}
</div>