2017-06-02 40 views
3

我的應用程序有一個主要儀表板,由8個不同的部分視圖組成;每個支持自己的視圖模型和我的控制器我只是打電話在單個視圖中組織多個ASP .Net MVC查看模型的最佳方式是什麼?

public ActionResult mainDashboard(){ 
return View() 
} 

返回儀表板。我的問題是,是否會建議創建一個儀表板視圖模型,該模型還包含對部分視圖的視圖模型的引用?在這種情況下什麼被認爲是推薦的最佳實踐?

回答

3

Ohkk這裏是一個好主意,以及使用html.Action,而不是html.partial

這看起來更像是這樣的:

public ActionResult Dashboard() 
{ 
    return View(); 
} 

public PartialViewResult Clubs() 
{ 
    .... 
    return PartialView(db.Clubs.ToList());//this assumes the partial view is named Clubs.cshtml, otherwise you'll need to use the overload where you pass the view name 
} 

public PartialViewResult Alerts() 
{ 
    .... 
    return PartialView(db.Alerts.ToList()); 
} 

Dashboard.cshtml

<div class="dashboard_alerts">  
    @Html.Action("Alerts") 

<div class="dashboard_pending_clubs">  
    @Html.Action("Clubs") 
</div> 

<div class="dashboard_verified_members">  
    @Html.Action("Members") 
</div> 

OR

您將需要創建一個視圖模型特定的儀表盤頁面正是這將是更有效的方式

public class DashboardViewModel 
{ 
    public IEnumerable<GMC.Models.Clubs> Clubs { get; set; } 
    public IEnumerable<GMC.Models.MemberUsers> Users { get; set; } 
    public IEnumerable<GMC.Models.Alerts> Alerts { get; set; } 
} 

然後,在儀表板的操作方法,你會填充每個列表:

myModel.Users = db.MemberUsers.ToList(); 

... 你會那麼需要更新的觀點在這方面採取新的視圖模型

@model DashboardViewModel 

最後,從視圖中,您需要在數據傳遞給每個部分:

@Html.Partial("DashboardAlerts", Model.Alerts) 

@Html.Partial("DashboardClubs", Model.Clubs) 
+1

謝謝!非常好的答案! – LifeOf0sAnd1s

+0

很高興它有助於快樂編碼:) – Curiousdev

相關問題