我在将ViewModel传递到视图时遇到问题。
我的ViewModel:
namespace ImpactDBASPNet.Models
{
public class ComputerInfoViewModel
{
public List<string> CompanyList { get; set; }
public tbl_computerinfo entitymodeleffort { get; set; }
}
}
控制器:
public ActionResult Index()
{
var tbl_computerinfo = db.tbl_computerinfo.Include(t => t.tbl_equipment);
tbl_computerinfo = tbl_computerinfo.Where(c => c.Company == "Test Company");
List<string> companylist = new List<string>();
companylist.Add("Hello1");
companylist.Add("hello2");
ComputerInfoViewModel model = new ComputerInfoViewModel();
model.CompanyList = companylist;
model.entitymodeleffort = tbl_computerinfo;
return View(model);
}
我这样做主要是因为我需要在我的视图中传递下拉列表的列表,所以我需要传递实体框架模型和列表。我得到的错误是:
Error 1 Cannot implicitly convert type 'System.Linq.IQueryable<ImpactDBASPNet.Models.tbl_computerinfo>' to 'ImpactDBASPNet.Models.tbl_computerinfo'. An explicit conversion exists (are you missing a cast?) c:\impactdbaspnet\controllers\tbl_computerinfocontroller.cs 31 39 ImpactPortal
答案 0 :(得分:0)
属性entitymodeleffort
的类型为tbl_computerinfo
,但您为其分配了IEnumerable<tbl_computerinfo>
,从而导致错误。您需要使用返回单个FirstOrDefault()
对象的Single()
(或其中一个变体 - tbl_computerinfo
等)。
将代码更改为
public ActionResult Index()
{
var tbl_computerinfo = db.tbl_computerinfo
.Include(t => t.tbl_equipment)
.Where(c => c.Company == "Test Company")
.FirstOrDefault();
List<string> companylist = new List<string>() { "Hello1", "Hello2" }; // save a few lines of code
ComputerInfoViewModel model = new ComputerInfoViewModel();
model.CompanyList = companylist;
model.entitymodeleffort = tbl_computerinfo;
return View(model);
}
附注:由于companylist
用于dropdownlist
,因此您可以设置属性SelectList
public SelectList CompanyList { get; set; }
和
model.CompanyList = new SelectList(companylist);
并在视图中
@Html.DropDownListFor(m => m.entitymodeleffort.SomeProperty, Model.CompanyList, ...)