【发布时间】:2020-09-10 16:32:43
【问题描述】:
我有一个自定义查询,我想通过视图模型传递给视图。我可以将查询直接传递给视图并且它可以工作,但是当我尝试使用视图模型将它传递给视图时出现错误。我知道必须有一个简单的答案,但如果我能弄清楚我会被绞死的。
班级
namespace TADSVer2_1.Models
{
public class TailNo
{
public string TailNos { get; set; }
public string Base { get; set; }
public string ACType { get; set; }
}
}
查询 查询工作正常,我得到了我需要的数据。
var test3 = _context.Aircrafts.Where(c => c.BaseId == 4).Include(c => c.ACType).Include(c => c.Base)
.Select(c => new TailNo {
TailNos = c.TailNumber,
ACType = c.ACType.Type,
Base = c.Base.Name }).ToList();
景色
@model IEnumerable<TADSVer2_1.ViewModels.AircraftViewModel>
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<ul>
@foreach (var i in Model)
{
<li>
@i.TailNos " " @i.Base " " @i.ACType
</li>
}
</ul>
上面的代码工作正常,但是当我使用视图模型时,我得到了如下所列的错误。
视图模型
namespace TADSVer2_1.ViewModels
{
public class AircraftViewModel
{
public IEnumerable<TailNo> TailNo { get; set; }
}
}
我收到的第一条错误消息是:
'AircraftViewModel' does not contain a definition for 'TailNos' and no extension method 'TailNos' accepting a first argument of type 'AircraftViewModel' could be found (are you missing a using directive or an assembly reference?)
所以我从视图中删除了 IEnumerable,我得到了这个错误:
foreach statement cannot operate on variables of type 'AircraftViewModel' because 'AircraftViewModel' does not contain a public instance definition for 'GetEnumerator'
所以我替换了视图中的 IEnumerable 并在视图模型中尝试了这个并得到了这个编译错误
public TailNo TailNo { get; set; }
Error CS1061 'AircraftViewModel' does not contain a definition for 'TailNos' and no accessible extension method 'TailNos' accepting a first argument of type 'AircraftViewModel' could be found (are you missing a using directive or an assembly reference?) TADSVer2_1 D:\Programing_ Examples\MVC_Examples\MVC Exercises\TADSVer2_1\TADSVer2_1\Views\Aircraft\Index.cshtml 12 Active
所以我被困在如何让自定义查询使用视图模型。感谢您的帮助。
【问题讨论】:
标签: asp.net-mvc entity-framework linq razor