母版页与部分视图

1.Renderbody

  占位符,添加在母版页中,输出子页面的内容

  母版页Master:

<html>
<body>
    这里是母版页内容1
    <br />
    @RenderBody()
    <br />
    这里是母版页内容2
</body>
</html>

  子页About:

@{
    ViewData["Title"] = "About";
    Layout = "~/Views/Shared/Mister.cshtml";
}

<h2>这里是子页内容</h2>

  运行结果

    

2.RenderSection

  实现子页面内容个性化,可以实现

    母版页内容 -》  子页内容  -》  母版页内容  -》  子页内容  -》  母版页内容

  各种排版需求,这个是非常灵活的

  修改一下母版页Master

<html>
<body>
    这里是母版页内容1
    <br />
    @RenderSection("Section1")
    <br />
    @RenderBody()
    <br />
    @RenderSection("Section2")
    <br />
    这里是母版页内容2
</body>
</html>

  视图如下:

@{
    ViewData["Title"] = "About";
    Layout = "~/Views/Shared/Mister.cshtml";
}

<h2>这里是子页内容</h2>

@section Section1{
    <h2>这里是Section1的内容</h2>
}
@section Section2{
    <h2>这里是Section2的内容</h2>
}

  结果:

    

   如果我们有点页面不想实现RenderSection中的内容,可以添加一个参数false

    @RenderSection("Section1",false)

  这样,Section1就变成非必要的,也就是如果没有内容输入也不会报错

3.部分共享视图
  如果我们需要在些许页面加入部分视图
  可以新建一个分部视图Partial
<h3>这是部分共享视图</h3>

  视图内容如下:

@{
    ViewData["Title"] = "About";
    Layout = "~/Views/Shared/Mister.cshtml";
}

<h2>这里是子页内容</h2>

@section Section1{
    <h2>这里是Section1的内容</h2>
}
@section Section2{
    <h2>这里是Section2的内容</h2>
}

@Html.Partial("~/Views/Shared/Partial.cshtml")

  结果:

    

 

 

总结:
  母版页用于内容共享
  分部视图倾向于页面局部呈现,比如局部刷新

  母版页不能单独使用
  分部视图可以单独打开,可以在控制器使用return PartialView("
~/Views/Shared/Partial.cshtml")返回这个分部视图
posted @ 2018-07-16 17:45  wskxy  阅读(235)  评论(0)    收藏  举报