2011-01-19 18 views

回答

45

Razor中的內容佔位符的等價物是章節。

在你_Layout.cshtml:

<head> 
@RenderSection("Styles", required: false) 
</head> 

然後在您的內容頁:

@section Styles { 
    <link href="@Url.Content("~/Content/StandardSize.css")" /> 
} 

另一種解決辦法是把你的風格融ViewBag/ViewData的:

在您的_Layout.cshtml中:

<head> 
    @foreach(string style in ViewBag.Styles ?? new string[0]) { 
     <link href="@Url.Content(style)" /> 
    } 
</head> 

而且在內容頁:

@{ 
    ViewBag.Styles = new[] { "~/Content/StandardSize.css" }; 
} 

這工作,因爲視圖頁面獲取佈局之前執行。

-2

令人驚訝的是(對我來說),asp:ContentPlaceHolder確實有效。似乎非常unrazorish雖然。我想知道還有別的辦法嗎?

具體來說,你把你的_layout.cshtml <asp:ContentPlaceHolder ID="HeadContent" runat="server" />

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server"> 
    <link href="@Url.Content("~/Content/StandardSize.css")" rel="stylesheet" type="text/css" /> 
</asp:Content> 

在您的視圖。

+0

它只在你看來,它的工作原理。你看過生成的HTML嗎? – marcind 2011-01-19 20:09:09

+0

你是對的。我剛看到我想要的樣式被應用,但我沒有檢查HTML。我想知道如何使用Razor處理服務器標籤。 – JohnOpincar 2011-01-19 20:56:16

相關問題