【发布时间】: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)。