我正在尝试将ModelView变量从控制器传递给视图,但是不幸的是,视图不允许我访问变量。我在下面提到代码。
这是ViewModel:
public class AuctionViewModels
{
public List<Auction> AllAuction { get; set; }
public List<Auction> PromotedAuction { get; set; }
}
这是Controller动作,它将数据传递到View:
public ActionResult Index()
{
AuctionViewModels vmodel = new AuctionViewModels();
vmodel.AllAuction = service.GetAllAuction(); //If we need to send more then 1 model to views
vmodel.PromotedAuction = service.GetPromotedAuction();
return View(vmodel);
}
这是视图:
@model List<DealDouble.Web.ViewModels.AuctionViewModels>
@foreach (var auction in Model.AllAuction )
{
<a href="#"><img class="card-img-top" src="http://placehold.it/700x400" alt=""></a>
}
这是错误:
CS1061: 'List<AuctionViewModels>' does not contain a definition for
'AllAuction' and no extension method 'AllAuction' accepting a first
argument of type 'List<AuctionViewModels>' could be found (are you missing
a using directive or an assembly reference?)
有人可以告诉我我实际上在做什么错吗?
答案 0 :(得分:2)
更改
@model List<DealDouble.Web.ViewModels.AuctionViewModels>
收件人
@model DealDouble.Web.ViewModels.AuctionViewModels
那么您将可以foreach(var auction in Model.AllAuction)
答案 1 :(得分:2)
您在行中有错误:
@model List<DealDouble.Web.ViewModels.AuctionViewModels>
您通过(作为模型)类,而不是列表。列表不包含诸如AllAuction之类的属性。尝试将此行替换为这一行:
@model DealDouble.Web.ViewModels.AuctionViewModels
答案 2 :(得分:1)
应该只是
@model DealDouble.Web.ViewModels.AuctionViewModels
您只传入该对象的一个实例,然后遍历AllAuction
属性。
答案 3 :(得分:0)
您要实例化包含两个字段的单个对象,这两个字段都是列表:
AuctionViewModels vmodel = new AuctionViewModels();
vmodel.AllAuction = service.GetAllAuction(); /
vmodel.PromotedAuction = service.GetPromotedAuction();
但是将其视为视图中的列表
@model List<DealDouble.Web.ViewModels.AuctionViewModels>
您需要将以上内容更改为:
@model DealDouble.Web.ViewModels.AuctionViewModels
然后您可以遍历两个字段
@foreach (var auction in Model.AllAuction ){}
@foreach (var auction in Model.PromotedAuction ){}