MVC Controller类可以有多个IEnumerable吗?

时间:2014-01-11 13:52:54

标签: c# asp.net asp.net-mvc asp.net-mvc-3 asp.net-mvc-4

我可以做两个LINQ查询,然后将每个查询的结果作为IEnumerable返回,或者查询是否需要合并,你将如何实现?

1 个答案:

答案 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操作返回的列表。