2013-05-07 20 views
1

问题在布局模板组可变

在ASP.NET MVC(和具体地与剃须刀),请问部分(或“子内的一个组中的变量的值-template“)并在主(或布局)模板中访问该值?ASP.NET MVC - 从部分或身体

目标

我想保持资产(样式表和JavaScript文件)的列表,并能够从谐音内添加到列表中。然后,应该在主版面中访问这些资产,以将其包含在页面的<head/>(样式表)或<body/>(JavaScript文件)末尾附近。这提供了将模块存储在包含所有必要资产的部分中的优雅方式。

我的尝试

下面是我尝试过的样式表。预期的结果是,标题中将包含global.cssview_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> 
+0

[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

+0

这些答案都没有回答你问的问题。它们只是通过儿童来设置CSS或脚本的方法,并且对于在部分中设置变量并在父级中使用它(您问到的问题)没有任何关系。 – 2013-05-07 01:14:17

回答

3

你不能。布局模板在部分之前呈现。您在局部设置的任何变量都会设置得太迟而无法让布局知道它在那里。

这似乎是一个过于复杂的解决方案。你为什么不使用MVC提供的Web优化工具?

+5

说你不能做某事不会回答如何去做。只是因为你不知道怎么不意味着这是不可能的。 – 2013-05-07 01:05:04

+1

@AndrewAshbacher - 绝对不可能在部分中设置c#变量并在布局中使用它。降低我回答你问的问题(而不是你似乎意味的问题)是非常差的网络礼仪。是的,您可以通过多种方式在布局中设置脚本,但不能通过您特别提出的问题。 – 2013-05-07 01:13:04

+0

够公平的。我一定会在将来适当地说出实际的问题。这就是说,这不是一个过于复杂的解决方案,因为它简化了其他地方的大量代码。我们正在使用[类似的东西](https://github.com/ServiceStack/Bundler)进行WebOptimization。但是,我们也希望模块化并提高代码的可重用性。 – 2013-05-07 16:01:59