2012-05-05 130 views
8

鑑於視圖層次結構:Index.cshtml - > _Layout.cshtml - > _MasterLayout.cshtml:MVC:如何使用(渲染)從父(主)視圖(佈局視圖)部分?

_MasterLayout.cshtml - 所述一組段,我想在主佈局(下文)

@section javascriptLinks { 
<script src="~/client/vendor/require-jquery.js" data-main="~/client/main.js" type="text/javascript"></script> 
} 
@RenderBody() 
使用

_Layout.cshtml - 現場實際總體佈局

@{ 
    Layout = "~/Views/Shared/_MasterLayout.cshtml"; 
} 

<!doctype html> 
<html> 
<!-- actual site layout here --> 
<body> 
@RenderBody() 
@RenderSection("javascriptLinks") 
</body> 
</html> 

Index.cshtml - 一些具體的頁面特定標記

拆分_Layout.cshtml和_MasterLayout.cshtml的想法是代碼共享。我有一種庫/框架和_MasterLayout屬於這個庫。 _Layout.cshtml是一個具體的應用程序站點主佈局。

不幸的是,這種模式不起作用。在渲染過程中_Layout.cshtml不會從_MasterLayout.cshtml中看到部分。

有沒有什麼辦法可以在這種情況下使用部分(從父視圖中獲取它們而不是從子視圖中獲取)?

我可以看到的一個可能的解決方案是爲_MasterLayout.cshtml中的每個部分創建單獨的頁面,並在_Layout中調用@RenderPage。但是,我想要一個共享資源(_MasterLayout.cshtml)。

回答

4

試着扭轉操作。 我的意思是這樣的:

_MasterLayout.cshtml:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8" /> 
    @RenderSection("HeadSection", true) 
    <title>@ViewBag.Title</title> 
</head> 
<body> 
@RenderBody() 

// ...... 
// You could put your general scripts here 
<script src="~/client/vendor/require-jquery.js" data-main="~/client/main.js" type="text/javascript"></script> 
// Put true to enforce the sub layout to define Scripts section 
    @RenderSection("Scripts", true) 
</body> 
</html> 

_Layout.cshtml:

@{ Layout = "~/Views/_Shared/_LayoutMain.cshtml"; } 
@section HeadSection{ 
    // any thing you want 
    @RenderSection("HeadSection", false) 
} 
    @RenderBody() 
// ...... 
// Put false to make Scripts section optional 
@section Scripts{ 
    @RenderSection("Scripts", false) 
} 
+0

這是有道理的,但確實成爲_Layout.cshtml不自然的(而不是html標記它必須包含@section聲明的集合)。我希望_Layout.cshtml包含整個頁面佈局,並只從一些(容易共享的)源導入「標準」部分(即部分)。 – Shrike