MVC 创建母版 和使用

it2022-05-05  225

一.母板页_Layout.cshtml 类似于传统WebForm中的.master文件,起到页面整体框架重用的目地 1.母板页代码预览  

<!DOCTYPE html> <html>   <head>   <title>@ViewBag.Title</title>   <link href="@Url.Content("~/Content/zxc.css")" rel="stylesheet" type="text/css" />   <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>   </head>     <body>   @RenderBody()   </body> </html>

2.子页面标题的设置 虽然多个子页面可以引用同一个母板页,但不同的页面标题可以单独设置。@ViewBag.Title 即是一个标题的占位符,在Control里或页面中给该标题的变量赋值。

public ActionResult LayoutDemo_01() {   ViewBag.Title = "布局页一";   return View(); } public ActionResult LayoutDemo_02() {   ViewBag.Title = "布局页二";   return View(); }

3.子页面主内容的设置  页面主内容是由@RenderBody()来标识的。子页面的内容直接替换到该方法处。

//第一个页面 @{   Layout = "~/Views/Shared/_Layout.cshtml"; } 这里是layoutg一的内容 //第二个页面 @{   Layout = "~/Views/Shared/_Layout.cshtml"; }

4.子页面其他内容的设置

由于母板面的内容大多数不会是连续的,如下代码所示:

<!DOCTYPE html> <html>   <head>   <title>@ViewBag.Title</title>   <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />   <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>   </head>   <body>     <br />     @* 主要部分*@     @RenderBody()     <br />     <br />     @*其他部份内容*@     @RenderSection("MasterPart", false)   </body> </html>

此时我们使用@RenderSection定义占位符子页面实现,@RenderSection方法接受两个参数:("名称","是否是必须的"),如果是必须的那么子页面必须实现该方法,否则会报错。

子页面代码如下:

@{   Layout = "~/Views/Shared/_Layout.cshtml"; } 这里是layoutg一的内容 @section MasterPart{   这里是母板页的第二部分 }

@section+空格+名称{内容}来实现母板页内容的替换。


最新回复(0)