我正在尝试查询数据库并将这些结果存储在模型中,其中一列是数字,一列是字符串数据:
型号:
using System.Data.Entity;
namespace Portal.Models
{
public class CompanyListId
{
public int Id { get; set; }
public string CompanyName { get; set; }
}
public class CompanyListIdDbContext : DbContext
{
public DbSet<CompanyListId> Contacts { get; set; }
}
}
控制器:
public PartialViewResult SelectCompanyFromDropdown()
{
using (var dc = new CompanyListIdDbContext())
{
var content = from p in db.Companies
select new { p.CoId, p.CompanyName };
}
//I want to set Models ID = to each instance of coid
//Set Models CompanyName to each instance of companyname
return PartialView();
}
我不知道从哪里开始,我试图从这个模型中删除。
我将代码块更新为:
public PartialViewResult SelectCompanyFromDropdown()
{
using (var dc = new CompanyListIdDbContext())
{
var content = from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
};
return PartialView(content.ToList());//giving an error
}
}
我的观点是:
@model Portal.Models.CompanyListId
@Html.DropDownListFor(m => m.CompanyName, Model.CompanyName)
这似乎也不起作用,我需要从我想到的动作中返回我的模型,这样视图就可以正确地使用数据。
答案 0 :(得分:8)
您应该将结果投射到您的班级CompanyListId
var content = from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
};
编辑:
我不确定错误,但您可以尝试:
public PartialViewResult SelectCompanyFromDropdown()
{
List<CompanyListId> content = null;
using (var dc = new CompanyListIdDbContext())
{
content = (from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
}).ToList();
}
return PartialView(content);
}
答案 1 :(得分:3)
您可以像这样选择一个新的类实例:
var content = from p in db.Companies
select new CompanyListId
{
Id = p.CoId,
CompanyName = p.CompanyName
};