問題在佈局模板組可變
在ASP.NET MVC(和具體地與剃鬚刀),請問部分(或「子內的一個組中的變量的值-template「)並在主(或佈局)模板中訪問該值?ASP.NET MVC - 從部分或身體
目標
我想保持資產(樣式表和JavaScript文件)的列表,並能夠從諧音內添加到列表中。然後,應該在主版面中訪問這些資產,以將其包含在頁面的<head/>
(樣式表)或<body/>
(JavaScript文件)末尾附近。這提供了將模塊存儲在包含所有必要資產的部分中的優雅方式。
我的嘗試
下面是我嘗試過的樣式表。預期的結果是,標題中將包含global.css
和view_post.css
,但僅顯示global.css
。我的理解是,這是因爲佈局在模板之前呈現。
助手/ AssetHelper.cs
namespace MyApp.Helpers
{
public static class AssetHelper
{
private static SortedSet<string> StyleSheets(this HtmlHelper helper)
{
if (helper.ViewBag._styleSheets == null)
helper.ViewBag._styleSheets = new SortedSet<string>();
return helper.ViewBag._stylesheets as SortedSet<string>;
}
public static MvcHtmlString AddStyleSheet(this HtmlHelper helper, string styleSheet) {
helper.StyleSheets().Add(styleSheet);
return new MvcHtmlString("");
}
public static MvcHtmlString RenderStyles(this HtmlHelper helper)
{
StringBuilder output = new StringBuilder();
string template = "<link rel=\"stylesheet\" type=\"text/css\" href=\"{0}\" />";
foreach (string styleSheet in helper.StyleSheets())
output.Append(String.Format(template, styleSheet));
return new MvcHtmlString(output.ToString());
}
}
}
查看/共享/ Layout.cshtml
@using MyApp.Helpers
<html>
<head>
...
@Html.AddStyleSheet("global.css")
@Html.RenderStyles()
</head>
<body>
...
@RenderBody
...
</body>
</html>
查看/職位/ View.cshtml
@using MyApp.Helpers
@Html.AddStyleSheet("view_post.css")
<h2>...</h2>
<p>...</p>
[these]的重複(http://stackoverflow.com/questions/5312759/trying-to-add-js-and-css-to-layout-file-in-mvc-3-razor-website-from -partial-view?rq = 1)[three](http://stackoverflow.com/questions/5981490/how-to-render-javascript-into-masterlayout-section-from-partial-view/6671766#6671766)[問題](http://stackoverflow.com/questions/5110028/add-css-or-js-files-to-layout-head-from-views-or-partial-views/7343340#7343340)。發佈我的問題後,我只需要**相關**邊欄。 :) – 2013-05-07 01:02:35
這些答案都沒有回答你問的問題。它們只是通過兒童來設置CSS或腳本的方法,並且對於在部分中設置變量並在父級中使用它(您問到的問題)沒有任何關係。 – 2013-05-07 01:14:17