在MVC4视图中链接多个类

时间:2012-09-02 00:25:11

标签: asp.net-mvc ef-code-first

假设我有一个这样的模型(从原文中简化):

public class Location
{
    public int ID { get; set; }
    public string BinNumber { get; set; }
}

public class Item
{
    public int ID { get; set; }
    public string Description { get; set; }
    public virtual Location Bin { get; set; }
}

public class LineOnPickList
{
    public int ID { get; set; }
    public virtual Item Item { get; set; }
}

在LineOfPickList创建视图中,通常要做的是有一个下拉列表,列出所有项目描述,并在单击创建时将所选项目放在新创建的LineOnPickList记录中。

然而,我需要做的是显示位置BinNumbers的下拉列表,但仍然在新创建的LineOnPickList记录中将该项与该位置相关联。

怎么做?

1 个答案:

答案 0 :(得分:2)

为您的下拉列表定义视图模型

public class ItemViewModel
{
    public int ID { get; set; }
    public string BinNumber { get; set; }
}

然后在控制器操作中构建下拉列表数据,如下所示

public class CreateLineOnPickListViewModel
{
    public int ItemId { get; set; }
    public IEnumerable<ItemViewModel> Items { get; set; }
}

public ActionResult Create()
{
    var model = new CreateLineOnPickListViewModel();
    model.Items = db.Items
          .Select(i => new ItemViewModel { ID = i.ID, BinNumber = i.Bin.BinNumber });

    return View(model);
}

然后在你看来

@model CreateLineOnPickListViewModel

@Html.DropDownListFor(m => m.ItemId, new SelectList(Model.Items, "ID", "BinNumber"), "-")

然后你的控制器中的post action方法看起来像这样

public ActionResult Create(CreateLineOnPickListViewModel model)
{
    var item = new Item { ID = model.ItemID };
    db.Items.Attach(item);

    var lineOnPickList = new LineOnPickList { Item = item };

    db.SaveChanges();

    return View(model);
}