為Asp.net MVC中的RenderSection設置默認內容


1. RenderSection的簡單介紹

Asp.net MVC中提供了RenderSection方法,這樣就能夠在Layout中定義一些區塊,這些區塊留給使用Layout的view來實現
比如我們定義的Layout如下, 定義了一個”Footer”的section, 把這個section留給各個view去填充。

<!DOCTYPE html>
<html>
     <head>
           <title>Sample Layout</head>
     <body>
            <div>@RenderBody()</div>
            <footer>@RenderSection("Footer")</footer>
     </body>
</html>

 在使用該Layout的view中,可以這樣來填充“Footer” section.

@{
    Layout = "MyLayout.cshtml";

}
<h1>Main Content!</h1>
@section Footer {
    This is the footer.
} 

RenderSection方法還有一個參數, 如果使用RenderSection(“Footer”, false) ,則表示,這個section Footer,view中不是必須要實現。

2,在Layout中定義一個具有默認值的Section

問題的由來是這樣的,項目中使用到了Jquery 1.4.4, 想升級到Jquery到更高的版本,但是由於已有的一些js代碼只能兼容Jquery1.4.4, 所以沒有辦法簡單的把Jquery的引用在Layout中直接替換到更高版本。

這個時候,我想到了section, 不如在Layout中定義一個Jquery的section, 新開發的頁面在這個section里面使用更高版本的Jquery, 而原有的頁面就還是用舊版本的.
這個section應該有個默認值,也就是就的Jquery引用,新的view中只要替換就可以了。

無奈,MVC中默認的RenderSection沒有提供這種實現,於是,通過擴展RenderSection方法,實現了該功能。

3, 具體的實現代碼

定義一個靜態類WebPageBaseExtension, 擴展RenderSection方法

public static class WebPageBaseExtension
{
       public static HelperResult RenderSection(this WebPageBase webPage, string name, Func<dynamic, HelperResult> defaultContents)
       {
           if (webPage.IsSectionDefined(name))
           {
               return webPage.RenderSection(name);
           }
           return defaultContents(null);
       }
}

在Layout中使用該方法,定義默認section內容

<head>

@this.RenderSection("Jquery", @<script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>)
   <script src="@Url.Content("~/Scripts/jquery-ui.min.js")" type="text/javascript"></script>

………

</head>

在新開發的頁面上,覆蓋默認section, 使用新的版本的Jquery

@section Jquery
{
    <script src="@Url.Content("~/Scripts/jquery-1.9.min.js")" type="text/javascript"></script>
}

這樣就大功告成了,新版本的Jquery就能夠應用到新頁面中了,以后再慢慢修改舊的頁面,也遷移到新版本的Jquery, 最后就可以移除掉整個Jquery section,一步一步達到漸進升級的過程。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM