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