所以我有我的模特
public class AgencyAll
{
public Agency Agency { get; set; }
public AgencySector AgencySector { get; set; }
public AgencyExpertise AgencyExpertise { get; set; }
}
它引用了其他模型,因此我可以将它们传递到我的视图中
示例-代理商模型
public partial class Agency
{
public int id { get; set; }
public System.DateTime created { get; set; }
public int createdby { get; set; }
public string createdbytype { get; set; }
public System.DateTime lastupdated { get; set; }
public int lastupdatedby { get; set; }
public string lastupdatedbytype { get; set; }
public bool deleted { get; set; }
public string name { get; set; }
public string address { get; set; }
}
AgencySector和AgencyExpertise仅包含代理商ID和其他ID(部门或专业知识),因为这是多对多的关系
部分观点
@model AgencyAll
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<div class="form-group">
Sector:
@Html.DropDownListFor(model => model.AgencySector.sectorid, (SelectList) ViewBag.SectorList, new {@class = "form-control"})
</div>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<div class="form-group">
Specialisation:
@Html.DropDownListFor(model => model.AgencyExpertise.expertiseid, (SelectList) ViewBag.SpecialismList, new {@class = "form-control"})
</div>
</div>
如您所见,我可以很好地称呼不同型号
我的问题在这里发生
public ActionResult ViewData(int id)
{
ViewBag.CountyList = new SelectList(GetCountyList(), "Value", "Text");
ViewBag.SectorList = new SelectList(GetSectorList(), "Value", "Text");
ViewBag.SpecialismList = new SelectList(GetSpecialisationList(), "Value", "Text");
return View(_db.Agencies.FirstOrDefault(x => x.id == id));
}
具体来说,这行; return View(_db.Agencies.FirstOrDefault(x => x.id == id));
我正在尝试返回URL ViewData /(id)的代理数据,但是由于视图的模型是AgencyAll,因此无法将数据集分配给模型,因为该模型未引用表,而是引用引用表的多个模型。返回声明期望该视图具有Agency模型,而不是AgencyAll。
我无法弄清楚我需要替换return View(_db.Agencies.FirstOrDefault(x => x.id == id));
以便将数据从类传递到具有表模型的模型以显示数据的情况,
任何帮助将不胜感激。
答案 0 :(得分:0)
您需要为视图提供期望的模型,即 AgencyAll 。目前,您正在提供一个 Agency 对象。
将您的代码更改为以下内容:
public ActionResult ViewData(int id)
{
ViewBag.CountyList = new SelectList(GetCountyList(), "Value", "Text");
ViewBag.SectorList = new SelectList(GetSectorList(), "Value", "Text");
ViewBag.SpecialismList = new SelectList(GetSpecialisationList(), "Value", "Text");
var viewModel = new AgencyAll {
Agency = _db.Agencies.FirstOrDefault(x => x.id == id),
AgencySector = _db.AgencySectors.FirstOrDefault(),
AgencyExpertise = _db.AgencyExpertises.FirstOrDefatul()
}
return View(viewModel);
}