在MVC中为实体创建下拉列表

时间:2015-01-15 14:00:11

标签: asp.net-mvc asp.net-mvc-5

我是MVC的新手,并且很难搞清楚一些“基本”的东西 我有一个ViewModel形状如下:

public class ProjectViewModel
{
    public int Id { get; set; }

    [Required]
    public string Title { get; set; }

    [Required]
    public string Description { get; set; }

    public DateTime CreatedDate { get; set; }

    [Required]
    [Display(Name = "Final due date")]
    public DateTime FinalDueDate { get; set; }

    [Required]
    [Display(Name = "Attached equipment")]
    public Equipment AttachedEquipment { get; set; }
}

在我的Create视图中,我希望能够从下拉列表中选择AttachedEquipment的值。我的数据库中有一张表,里面有所有可用的设备 我知道有一个@Html助手@Html.DropDownListFor可以达到这个目的。但是我没有看到如何从数据库中获取值并将它们吐出到我的视图中。

我的ProjectController看起来像这样:

private AdventureWorks db = new AdventureWorks();

// GET: Project
public ActionResult Index()
{
    return View();
}

[HttpGet]
public ActionResult Create()
{
    // I'm guessing this is where I need to do some magic
    return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ProjectViewModel model)
{
    if (ModelState.IsValid)
    {
        var project = new Project
        {
            Title =  model.Title,
            Description = model.Description,
            CreatedDate = DateTime.Now,
            FinalDueDate = model.FinalDueDate,
            Equipment = model.Equipment
        };

        db.Projects.Add(project);
        db.SaveChanges();
        return RedirectToAction("Index");
    }

    return View(model);
}

如何将我的数据库中的Equipment值加载到Create视图的下拉列表中?

1 个答案:

答案 0 :(得分:0)

由于您无法将下拉列表绑定到复杂对象AttachedEquipment,我会更改视图模型以包含所选设备的属性,并选择SelectList选项

public class ProjectViewModel
{
  public int Id { get; set; }
  [Required]
  public string Title { get; set; }
  [Required]
  public string Description { get; set; }
  public DateTime CreatedDate { get; set; }
  [Required]
  [Display(Name = "Final due date")]
  public DateTime FinalDueDate { get; set; }
  [Required(ErrorMessage="Please select equipment)]
  public int? SelectedEquipment { get; set; }
  public SelectList EquipmentList { get; set; }
}

控制器

public ActionResult Create()
{
  ProjectViewModel model = new ProjectViewModel();
  // Assumes your Equipments class has properties ID and Name
  model.EquipmentList = new SelectList(db.Equipments, "ID", "Name");
  return View(model);
}

查看

@model ProjectViewModel
@using(Html.BeginForm())
{
  ....
  @Html.DropDownListFor(m => m.SelectedEquipment, Model.EquipmentList, "--Please select--")
  ....
}

或者,您可以绑定到m => m.AttachedEquipment.ID(假设Equipment包含属性ID