一、Views文件夾 -> Shared文件夾下的 _Layout.cshtml 母版頁
@RenderBody
當創建基于_Layout.cshtml布局頁面的視圖時,視圖的內容會和布局頁面合并,而新創建視圖的內容會通過_Layout.cshtml布局頁面的@RenderBody()方法呈現在標簽之間。
@RenderPage
從名稱可以猜出來這個方法是要呈現一個頁面。比如網頁中固定的頭部可以單獨放在一個共享的視圖文件中,然后在布局頁面中通過這個方法調用,用法如下:
@RenderPage(“~/Views/Shared/_Header.cshtml”)
帶參數
@RenderPage(“~/Views/Shared/_Header.cshtml”,new{parm="my",parm2="you")
調用頁面獲取參數:
//獲取 RenderPage() 傳遞過來的參數
@PageData["param"]
@RenderSection
布局頁面還有節(Section)的概念,也就是說,如果某個視圖模板中定義了一個節,那么可以把它單獨呈現出來
為了防止因缺少節而出現異常,可以給RenderSection()提供第2個參數:
@RenderSection("head", false)
或
@if (IsSectionDefined("head"))
{
@RenderSection("head", false)
}
else
{
<p>SubMenu Section is not defined!</p>
}
代碼如下:
<!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> <link href="@Url.Content(" rel="external nofollow" ~/Content/Site.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script> @RenderSection("head", required: true)@*View頁面自定義特定js/css使用*@ </head> <body> @RenderPage("~/Views/Shared/_Header.cshtml") @RenderBody() </body> </html> 二、創建視圖,使用母版頁
代碼如下:
@{ ViewBag.Title = "Index"; Layout = "~/Views/Shared/_Layout.cshtml"; } <h2>Index</h2> @section Head{ <script type="text/javascript"> $(function () { alert("hello jquery"); }); </script> } <p>執行C#普通語法</p><br /> @DateTime.Now.Date.ToShortDateString() <p>執行C#語句段</p> @{ List<string> list = new List<string> { "Mvc3", "Razor" }; list.Add(".Net4"); } <ul> @foreach(string s in list) { if (string.IsNullOrEmpty(s)) { <li>空</li> } else { <li>@s</li> } } </ul> 三、生成頁面的源代碼
<!DOCTYPE html><html><head> <title>Index</title> <link href="/Content/Site.css" rel="external nofollow" rel="stylesheet" type="text/css" /> <script src="/Scripts/jquery-1.4.4.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function () { alert("hello jquery"); }); </script></head><body> <h2>Index</h2><p>執行C#普通語法</p><br />2013/3/11<p>執行C#語句段</p><ul> <li>Mvc3</li> <li>Razor</li> <li>.Net4</li></ul> </body></html>
新聞熱點
疑難解答
圖片精選