MVC实体框架DropDownListFor<> [英] MVC Entity Framework DropDownListFor<>
问题描述
我想遵循最佳的MVC最佳实践来创建DropList。
I would like to follow best MVC best practise for creating DropLists.
我有3个模型(为此我将它们缩减了)
I have 3 Models (I have cut them down for the purposes of this)
模型一
学生
public int ID {get;set;}
public string Name {get;set}
public Site SiteID {get;set;}
模型二
站点
public int ID {get;set;}
public string SiteName {get;set}
模型三
VM
Model Three VM
public int ID {get;set}
public student Students {get;set;}
public DateTime Date { get { return DateTime.Now; } }
public bool Criteria {get;set;}
在我的VM视图中,我是使用EditorFor html助手来填充我的VM和学生模型。该站点模型已预先填充在数据库种子中。
In my VM view I am using EditorFor html helpers to populate my VM and Student Models. The site model is pre populated at the database seed.
我正在寻找在VM视图中包括站点下拉列表的最佳方法,该列表将映射到我的学生
I am looking for the best way to include a dropdownlist of sites on my VM view, that will map to my student model.
如何正确设置模型来实现这一目标?
How to I correctly set up my models to achieve this?
推荐答案
简而言之,您需要 DropDownListFor 扩展方法,并将 List< Site>
放入视图模型。
In short, you want the DropDownListFor extension method and to put a List<Site>
into the view model.
演示您情况的小提琴。小提琴有更多细节。螺母和螺栓在这里:
Here is a Fiddle that demonstrates your case. The Fiddle has more details. The nuts and bolts are here:
public class MyViewModel
{
public MyViewModel()
{
this.Sites = new List<Site>();
}
public int ID { get; set;}
public Student Students { get; set; }
public DateTime Date { get { return DateTime.Now; } }
public bool Criteria { get; set; }
public List<Site> Sites { get; set; }
}
视图-使用 DropDownListFor
View - Use DropDownListFor
@Html.DropDownListFor(m => m.Sites,
new SelectList(Model.Sites, "ID", "SiteName"))
在伪代码中,上面说的是
In psuedo-code, the above says
- 模型中的
站点
对象包含要显示的属性。 - 使用模型中的
站点
对象创建新的SelectList
。使用ID
属性作为数据值,并使用SiteName
属性作为数据文本。 - 基于上述信息创建一个下拉列表。
- The
Sites
object in the model contains the properties to display. - Create a new
SelectList
using theSites
object in the model. Use theID
property as the data value and theSiteName
property as the data text. - Create a drop down list based on the above info.
这只是将种子视图模型传递给视图。
This just passes a seeded view model to the view.
public ActionResult Index()
{
var vm = SeedFromDatabase();
return View(vm);
}
private MyViewModel SeedFromDatabase()
{
var vm = new MyViewModel();
vm.Sites.Add(new Site(0, "one"));
vm.Sites.Add(new Site(1, "two"));
vm.Sites.Add(new Site(2, "three"));
return vm;
}
这篇关于MVC实体框架DropDownListFor<>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!