[英]ASP.Net Scaffolded MVC Struggling to populate a dropdownlist with Entity Framework
I'm struggling to conceptualise this because every resource I have found on Google has presented a different way to do it. 我正在努力将其概念化,因为我在Google上找到的每个资源都提出了不同的实现方式。
I have, at the moment generated razor views pertaining to a scaffolded controller using entity Framework. 目前,我已经使用实体框架生成了与脚手架控制器有关的剃刀视图。 My controller looks like this:
我的控制器看起来像这样:
// GET: tbl_computerinfo
public ActionResult Index()
{
var tbl_computerinfo = db.tbl_computerinfo.Include(t => t.tbl_equipment);
tbl_computerinfo = tbl_computerinfo.Where(c => c.Company == "Company Name");
return View(tbl_computerinfo.ToList());
}
My Model is quite large but is just a generated entity framework model built on two tables linked with a foreign key tbl_computerinfo and tbl_equipment. 我的模型很大,但是只是一个生成的实体框架模型,该模型建立在两个表上,这些表与外键tbl_computerinfo和tbl_equipment链接。
There is a string field called company in tbl_computerinfo. tbl_computerinfo中有一个名为company的字符串字段。 I need to select all the unique company values in the database and then use that to populate a dropdown which would exist on the index view.
我需要在数据库中选择所有唯一的公司值,然后使用该值来填充索引视图中将存在的下拉列表。 The selection of a company on that dropdown list should then filter the results in index view to only pull back entries with that company name.
然后,在该下拉列表中选择一家公司,应在索引视图中过滤结果,以仅拉回具有该公司名称的条目。 Any pointing in the right direction would be gratefully appreciated.
任何朝着正确方向的指点将不胜感激。
You need to create a ViewModel: 您需要创建一个ViewModel:
public class ComputerInfoViewModel
{
public List<string> CompanyList {get; set;}
public ComputerInfo ComputerInfo {get; set;}
}
In your Index method you populate this and pass it to the View: 在您的Index方法中,将其填充并将其传递给View:
public ActionResult Index()
{
var model = new ComputerInfoViewModel
{
CompanyList = /* populate this with your list of companies */
ComputerInfo = /* populate this with what? */
};
return View(model);
}
In your View, you declare the model: 在您的视图中,声明模型:
@model ComputerInfoViewModel
And you can access the model properties for display using @Model.CompanyList
and @Model.ComputerInfo
您可以使用
@Model.CompanyList
和@Model.ComputerInfo
访问模型属性以进行显示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.