2011-09-21 21 views
0

我有兩個控制器我怎樣才能顯示在首頁/索引視圖MVCç#兩個的ActionResult

BloggsController:

//Last blogg from the database 
     public ActionResult LastBlogg() 
     { 
      var lastblogg = db.Bloggs.OrderByDescending(o => o.ID).Take(1); 

      return View(lastblogg); 
     } 

DishesController:

//Last recipe from the database 
public ActionResult LastRecipe() 
{ 
    var last = db.Dishes.OrderByDescending(o => o.ID).Take(1); 

    return View(last); 
} 

我想說明這樣做的結果在我的開始頁面上,Views/Home/index。

如果我把這個在我的HomeController:

//Last recipe from the database 
public ActionResult Index() 
{ 
    var last = db.Dishes.OrderByDescending(o => o.ID).Take(1); 

    return View(last); 
} 

我可以顯示結果我的起始頁的配方,但我怎麼顯示blogg和配方上OM起始頁的兩種結果?

回答

1

創建一個視圖模型,並添加Blogg和食譜。

public ActionResult Index() 
{ 
    var lastRecipe = db.Dishes.OrderByDescending(o => o.ID).Take(1); 
    var lastblogg = db.Bloggs.OrderByDescending(o => o.ID).Take(1); 

    var model = new BloggRecipeModel(lastRecipe, lastblogg); 

    return View(model); 

}

0

你可以簡單地在你的模型文件夾中創建一個自定義的ViewData,像這樣:

public class MyCustomViewData 
{ 
public Dish Dish {get;set;} 
public Blog Blog {get;set;} 
} 

然後在你的控制器:

ViewData.Model = new MyCustomViewData 
{ 
Dish = db.Dishes.OrderByDescending(o => o.ID).Take(1); 
Blog = db.Bloggs.OrderByDescending(o => o.ID).Take(1); 
} 

return View(); 

而在你的看法,將@Model屬性設置爲Models.MyCustomViewData並相應地處理它。

2

您應該爲LastBloggLastRecipe創建單獨的部分視圖,並將它們都放到您的主頁(需要新模型)。

相關問題