zoukankan      html  css  js  c++  java
  • @RenderSection 用法

    @RenderSection相当于在母版页占一个位置

    解决页面差异化的问题

    如JS何CSS的调用

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4     <title>后台管理</title>
     5  <link href="@Url.Content("~/Content/css.css")" rel="stylesheet" type="text/css" />
     6     <link href="@Url.Content("~/Content/style.css")" rel="stylesheet" type="text/css" />
     7     <script type="text/javascript" src="@Url.Content("~/Scripts/jquery-1.5.1.js")"></script>
     8 @RenderSection("HeadJs")
     9 </head>
    10 <body>
    11  @RenderBody()
    12 </body>
    13 </html>
    1  @section HeadJs{
    2 <script type="text/javascript" src="@Url.Content("")"></script>
    3     }

    但是当如果使用了_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>.

  • 相关阅读:
    Android开发如何定制framework层服务
    Intellij IDEA通过SVN导入基于Springboot的maven项目以及对已有项目做更新
    intelliJ IDEA 怎么添加本地的idea web项目
    Android热修复之AndFix使用教程
    iOS友盟分享的使用总结
    iOS 传感器集锦
    IOS CALayer的属性和使用
    Swift使用Alamofire实现网络请求
    Android踩坑随笔Fragment中onActivityResult方法不被调用
    上周热点回顾(4.30-5.6)团队
  • 原文地址:https://www.cnblogs.com/myhunter/p/2524349.html
Copyright © 2011-2022 走看看