zoukankan      html  css  js  c++  java
  • MVC3 Razor @RenderSection

    Mvc3的Razor视图引擎还提供了@RenderSection

    我的理解:@RenderSection在母版页中占个位,然后让使用此母版页的子页自己去呈现他们的Section。

    母版页_Layout.cshtml中定义@RenderSection("Section名")

    复制代码
    <body>
        
    <div id="header">@{Html.RenderAction("Menu", "Global");}</div>
        
    <div id="sideBar">
          @RenderSection("SubMenu")
        
    </div>
        
    <div id="container">@RenderBody()</div>
        
    <div id="footer">@{Html.RenderAction("Footer", "Global");}</div>
    </body>
    复制代码

    添加一个About.cshtml,使用_Layout.cshtml做母版页

    然后就可以在About.cshtml中定义"SubMenu"要呈现的内容

    复制代码
    @{
        ViewBag.Title = "About";
     }

     @section SubMenu{
        Hello This is a section implement in About View.
     }
    复制代码

    这里我在About.cshtml中实现了SubMenu,运行结果

    但是当如果使用了_Layout.cshtml做母版页的页没有实现Section的话,

    譬如我新建的Index.cshtml没有实现@section SubMenu{...},就会抛出异常

    这是因为我在_Layout.cshtml中使用的是@RenderSection("SubMenu")他要求所有子页都要实现,

    可以使用它的另外一个重载@RenderSection("SubMenu",false),第二个参数代表它不是必须的,就不会抛出异常。

    还有,当我在母版页中定义了@RenderSection("SubMenu",false)的时候,我希望当所有子页都没有实现这个Section

    的时候,母版页可以有自己的呈现内容,就可以用

    复制代码
     <div id="sideBar">
           @if (IsSectionDefined(
    "SubMenu"))
            {
                @RenderSection(
    "SubMenu"false)
            }
            
    else
            {
                
    <p>SubMenu Section is not defined!</p>
            }
     
    </div>
    复制代码

     这样当没有任何页面呈现Section的时候,就会默认显示定义的内容。

    还有一种比较灵活的方法,通过扩展方法来实现

    复制代码
     public static class Utility
        {
            
    public static HelperResult RenderSection(this WebPageBase page, string sectionName, Func<object, HelperResult> defaultContent)
            {
                
    if (page.IsSectionDefined(sectionName))
                {
                    
    return page.RenderSection(sectionName);
                }
                
    else
                {
                    
    return defaultContent(null);
                   
                }
            }
        }
    复制代码

     在母版页中

    @this.RenderSection("SubMenu", @<div>default section content</div>)

     OK了!没有呈现Section时,就默认显示<div>default section content</div>.

     

    原文来自:http://www.cnblogs.com/dragon_mail/archive/2011/06/30/2094884.html

  • 相关阅读:
    有点忙啊
    什么是协程
    HDU 1110 Equipment Box (判断一个大矩形里面能不能放小矩形)
    HDU 1155 Bungee Jumping(物理题,动能公式,弹性势能公式,重力势能公式)
    HDU 1210 Eddy's 洗牌问题(找规律,数学)
    HDU1214 圆桌会议(找规律,数学)
    HDU1215 七夕节(模拟 数学)
    HDU 1216 Assistance Required(暴力打表)
    HDU 1220 Cube(数学,找规律)
    HDU 1221 Rectangle and Circle(判断圆和矩形是不是相交)
  • 原文地址:https://www.cnblogs.com/acafaxy/p/2473877.html
Copyright © 2011-2022 走看看