【问题标题】:Creating dropdownlist for entity in MVC在 MVC 中为实体创建下拉列表
【发布时间】:2016-03-22 06:01:36
【问题描述】:

我是 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 视图的下拉列表中?

【问题讨论】:

  • @MarkShevchenko 好的,我得到了给出的例子。但这是否意味着我必须始终找到与所选值匹配的数据库条目?
  • 是的,你会的。使用 EF 很简单,但仍然很乏味。通常这个逻辑位于辅助类和方法中。在简单的应用程序中,您可以直接在模型中执行此操作。在复杂的应用程序中,最好将此逻辑推送到单独的层中(请参阅Model-View-Presenter pattern)。

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


【解决方案1】:

由于您无法将下拉列表绑定到复杂对象 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-22
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多