我可以做两个LINQ查询,然后将每个查询的结果作为IEnumerable返回,或者查询是否需要合并,你将如何实现?
答案 0 :(得分:5)
你的控制器可以从一个动作中返回多个IEnumerable。
这将按如下方式完成:
<强>视图模型强>
public class FooModel
{
public List<Category> Categories { get; set; }
public List<SubCategory> SubCategories { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Description { get; set; }
}
public class SubCategory
{
public int Id { get; set; }
public string Description { get; set; }
public int CategoryId { get; set; }
}
控制器操作
public ActionResult Index()
{
var model = new FooModel();
var categories = new List<Category>();
var subCategories = new List<SubCategory>();
categories.Add(new Category { Id = 1, Description = "Cat 1" });
categories.Add(new Category { Id = 2, Description = "Cat 2" });
subCategories.Add(new SubCategory { Id = 1, Description = "Sub-Cat 1", CategoryId = 1 });
subCategories.Add(new SubCategory { Id = 2, Description = "Sub-Cat 2", CategoryId = 2 });
model.Categories = categories;
model.SubCategories = subCategories.Where(s => s.Id == 1).ToList();
return View(model);
}
在上面FooModel
(视图模型)中包含两个从Controller Index
操作返回的列表。