2011-10-18 14 views
33

我想分開所有可以在部分中重用的東西,所以對我來說更容易保持。無法直接請求文件「〜/ Views/Position/Edit.cshtml」,因爲它調用了「RenderSection」方法

但是我得到這個異常: 文件「〜/查看/位置/ Edit.cshtml」不能直接要求,因爲它稱之爲「RenderSection」方法

我創建了一個名爲sections.cshtml與文件以下內容:

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

而在_layout.cshtml文件我把它改爲:

<head> 
    <meta charset="utf-8" /> 
    <title>@ViewBag.Title</title> 
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> 
    @RenderSection("scripts", required:false) 
    @*<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/modernizr-1.7.min.js")" type="text/javascript"></script>*@ 
</head> 

當我去到視圖中瀏覽器並檢查它僅顯示的源代碼:

<head> 
    <meta charset="utf-8" /> 
    <title>Edit</title> 
    <link href="/Content/Site.css" rel="stylesheet" type="text/css" /> 
</head> 
+0

爲什麼不乾脆把腳本到您的版式文件? – samack

+0

只是試圖學習如何使用mvc中的部分,但是這也是一個選項,但如果某些腳本將用於某些視圖以及其他視圖中的其他腳本,那該怎麼辦?部分會解決這個問題,但佈局文件不會解決它,對吧? –

+0

擺脫@RenderSection,只是把腳本放在......這是佈局文件的要點,以存儲這些在大多數頁面中常見的東西。 – samack

回答

32

RenderSection只能在佈局文件中存在(即,母版頁)...其目的是允許您可以直接請求的頁面定位佈局的各個部分(佈局是所有選擇使用它的頁面的公共文件),併爲這些不同部分提供內容。

如果你想分開這部分出來的東西是很多的網頁可重用的,你應該把它放在一個部分和替換像

@Html.Partial("Scripts") 
+1

請檢查編輯,我試圖使用佈局文件而不是部分視圖,它不工作,我也沒有得到例外。 –

+0

如果我將section要求更改爲true,它給了我這個例外:Section not defined:「scripts」,我是否需要將該部分放置在其他地方? –

+0

這是因爲您直接請求的文件需要將其中的部分標記爲@section script {....},其中包含內容以便在佈局文件中的內容@RenderSection(「腳本」)被稱爲...部分不是用於定義通用功能。部分是 –

12

的rendersection調用的東西或者你可以使用helper到單獨的代碼你更經常使用。特別是如果你不能使用sections,因爲提到了約束馬丁平坦。

@helper Scripts(){ 
    <script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script> 
    <script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script> 
} 

和用法就是:

<somehtml /> 
@Scripts() 
<somehtml /> 
+3

如果腳本應該放在標記中,該怎麼辦? –

相關問題