2012-05-05 11 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のセクションは表示されません。

このような場合にセクションを使用する方法はありますか(子ビューからではなく親ビューから取得する)?

私が見ることができる1つの可能な解決策は、_MasterLayout.cshtmlの各セクションに別々のページを作成し、_Rayoutの@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

関連する問題