![](/img/trans.png)
[英]Struggling with saving data to database in ASP.NET MVC with Entity Framework
[英]ASP.Net Scaffolded MVC Struggling to populate a dropdownlist with Entity Framework
我正在努力将其概念化,因为我在Google上找到的每个资源都提出了不同的实现方式。
目前,我已经使用实体框架生成了与脚手架控制器有关的剃刀视图。 我的控制器看起来像这样:
// 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());
}
我的模型很大,但是只是一个生成的实体框架模型,该模型建立在两个表上,这些表与外键tbl_computerinfo和tbl_equipment链接。
tbl_computerinfo中有一个名为company的字符串字段。 我需要在数据库中选择所有唯一的公司值,然后使用该值来填充索引视图中将存在的下拉列表。 然后,在该下拉列表中选择一家公司,应在索引视图中过滤结果,以仅拉回具有该公司名称的条目。 任何朝着正确方向的指点将不胜感激。
您需要创建一个ViewModel:
public class ComputerInfoViewModel
{
public List<string> CompanyList {get; set;}
public ComputerInfo ComputerInfo {get; set;}
}
在您的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);
}
在您的视图中,声明模型:
@model ComputerInfoViewModel
您可以使用@Model.CompanyList
和@Model.ComputerInfo
访问模型属性以进行显示
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.