问题在布局模板组可变
在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