2014-01-11 24 views
1

我可以做兩個LINQ查詢,然後將每個查詢的結果作爲IEnumerable返回,還是需要將查詢組合起來,以及如何完成這些查詢?MVC控制器類可以有多個IEnumerable嗎?

+0

IEnumerable是否有關聯?如果您只想將兩個數組返回,您可以使用.Join或.Concat。 – Jason

+0

如果你的意思是傳遞兩個數字,那麼視圖模型可能就是你要找的東西。 – scheien

+2

@JasonEvans,顯然沒有任何東西 - 就像沒人試過任何東西一樣。請記住,當沒有互聯網?! *兩邊都是上坡咕咕咕咕地...... * –

回答

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(視圖模型)包含返回的兩個列表從控制器Index的操作。

相關問題