MVCCheckBoxList适用于1对多的关系

时间:2017-08-17 23:34:11

标签: c# asp.net-mvc-5 models

我有一个班级与另一班级有1对多的关系。为此,我将使用类Car和类Gears。我需要创建一个注册汽车的表单,用户需要指定一个齿轮选择。

public class Car
{
   public int id { get; set; }
   public string desc { get; set; }
   public List<Gear> Gears { get; set; }
}
public class Gear
{
   public int gid { get; set; }
   public int gname { get; set; }
}

使用asp.net MVC 5,我有一个创建表单,我已将其搭建到Car模型中,并且在表单中,我希望有一个齿轮的复选框,

我还有一个ViewModel,我已经为我的复选框列表提供了如下内容:

public class GearsViewModel
{
    public Gear _gear {get; set; }
    public bool _isChecked {get; set;}
}

控制器看起来像:

  

从db上下文获取的Gears将是   “GearR”, “GEAR1”, “GEAR2”, “Gear3”, “GEAR4”, “Gear5”, “Gear6的”, “Gear7”

public action Create()
{
    ViewBag.Gears = new SelectList(db.Gears, "gid","gname");
    List<GearViewModel> _gears= new List<GearViewModel>();
    foreach(Gear G in ViewBag.Gears)
    {
        _gears.Add(new GearViewModel(G, false));
    }
    ViewBag.GearsCheckList = _gears.ToList();
    return View();
}

现在,这是我遇到的部分,是如何在CreateView中显示和捕获细节。

我需要有关如何设计“创建”表单以及如何捕获信息的帮助。

1 个答案:

答案 0 :(得分:2)

首先,视图模型在编辑时不应包含数据模型。您应该查看模型(根据需要添加验证和显示属性)

public class CarVM
{
    public int? ID { get; set; }
    public string Description { get; set; }
    public List<GearVM> Gears { get; set; }
}
public class GearVM
{
    public int ID { get; set; }
    public string Name { get; set; }
    public bool IsSelected { get; set; }
}

并且GET方法将是

public ActionResult Create()
{
    var gears = db.Gears;
    CarVM model = new CarVM
    {
        Gears = gears.Select(x => new GearVM
        {
            ID = x.gid,
            Name = x.gname
        }).ToList()
    };
    return View(model);
}

然后视图将

@model CarVM
....
@using (Html.BeginForm())
{
    ..... // elements for editing ID and Description properties of CarVM
    @for (int i = ; i < Model.Gears.Count; i++)
    {
        <div>
            @Html.HiddenFor(m => m.Gears[i].ID)
            @Html.HiddenFor(m => m.Gears[i].Name) // include if your want to get this in the POST method as well
            @Html.CheckboxFor(m => m.Gears[i].IsSelected)
            @Html.LabelFor(m => m.Gears.IsSelected, Model.Gears[i].Name)
        </div>
    }
    <input type="submit" .... />
}

然后在POST方法中

public ActionResult Create(CarVM model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    // To get the ID's of the selected gears
    IEnumerable<int> selected = model.Gears.Where(x => x.IsSelected).Select(x => x.ID);
    // Initialize your data models, save and redirect
}