Skip to main content
 首页 » 编程设计

c#之ASP.NET MVC之在部分或主体的布局模板中设置变量

2024年02月13日12telwanggs

问题

在 ASP.NET MVC(尤其是 Razor)中,如何在部分(或“子模板”)中设置变量的值并在主(或布局)模板中访问该值?

目标

我想维护 Assets 列表(样式表和 JavaScript 文件)并能够从部分中添加到列表中。然后应该可以在要包含在 <head/> 的主布局中访问 Assets (样式表)或接近 <body/> 的末尾页面的(JavaScript 文件)。这提供了一种将模块存储在包含所有必要 Assets 的部分中的优雅方法。

我的尝试

下面是我尝试过的样式表。预期的结果是 global.css和 view_post.css将包含在 header 中,但仅包含 global.css正在出现。据我了解,发生这种情况是因为布局在模板之前呈现。

Helpers/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()); 
        } 
 
    } 
} 

Views/Shared/Layout.cshtml

@using MyApp.Helpers 
 
<html> 
  <head> 
    ... 
    @Html.AddStyleSheet("global.css") 
    @Html.RenderStyles() 
  </head> 
  <body> 
    ... 
    @RenderBody 
    ... 
  </body> 
</html> 

Views/Posts/View.cshtml

@using MyApp.Helpers 
@Html.AddStyleSheet("view_post.css") 
 
<h2>...</h2> 
<p>...</p> 

请您参考如下方法:

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

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