如何在视图中设置多个对象?
public ActionResult Index()
{
var shops = this.context.shops.Select(q => new { q.id, q.name }).ToList();
var bikes = this.context.bikes.Select(q => new { q.id, q.name }).ToList();
return View(shops, bikes); // How to set two values in View()?
}
在View()中解析
@foreach (var r in Model.bikes)
{
<b>@r.name</b>
}
答案 0 :(得分:3)
一种方法是创建一个包含商店和自行车的强类型视图模型。其他选项可能是创建一个元组并作为模型传递给视图。我会先选择。
var tuple = new Tuple<shop, bike>(new shop(),new bike());
在你看来
@Model Tuple<shop,bike>
答案 1 :(得分:2)
您的模型类应包含商店和自行车的属性。也就是说,如果您使用强类型视图,它看起来就是这样。否则,您可以向ViewBag添加内容以供在视图中使用。
答案 2 :(得分:2)
您需要创建ViewModel
public class shopsAndbikes
{
public List<shop> shops {get;set;}
public List<bike> bikes {get;set;}
}
public ActionResult Index()
{
shopsAndbikes vm = new shopsAndbikes ()
{
var shops = this.context.shops.Select(q => new { q.id, q.name }).ToList();
var bikes = this.context.bikes.Select(q => new { q.id, q.name }).ToList();
}
return View(vm);
}
查看:
@model shopsAndbikes
@foreach (var r in Model.bikes)
{
<b>@r.name</b>
}
@foreach (var r in Model.shops)
{
<b>@r.name</b>
}