【问题标题】:ASP.NET MVC Razor and css blockASP.NET MVC Razor 和 css 块
【发布时间】:2026-01-09 02:00:02
【问题描述】:

我希望我的 css 样式块有一些灵活性,所以我决定注入一些服务器端代码,f.e.

#defaultGameContainer {
            position: relative;
            width: @(SiteConfig.Instance.Game.Width + "px");
            height: 600px;
            top: 100px;
            left: 50%;
            margin-left: -480px;
        }

但这似乎不起作用,我在 VS 中有一个错误,例如“意外的字符序列......” 我们是否仅限于在 css 中使用 Razor 语法? 谢谢。

【问题讨论】:

    标签: css asp.net-mvc razor


    【解决方案1】:

    实际上,您可以按照以下说明为特定的.cshtml 视图添加自定义CSS 块:

    首先,在 .cshtml 查看自定义 CSS 块中定义

    @section CustomCSS{ 
    <style>
        #floorsList > tbody > tr > td {
            vertical-align: middle
        }
    </style>
    }
    

    然后,您需要将这个 CustomCSS section 嵌入到 _layout.cshtml 文件中:

    <!DOCTYPE html>
    <html>
     <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>@ViewBag.Title - Your Application</title>
        @Styles.Render("~/Content/css")
        @Scripts.Render("~/bundles/modernizr")
        @RenderSection("Styles", false)
        <!--Consider the following line -->
        @RenderSection("CustomCSS", required: false)
     </head>
     <body>
     </body>
    </html>
    

    【讨论】:

    • 这仅限于布局
    【解决方案2】:

    mvc razor 视图引擎不解析 css/js 文件

    您可以创建返回纯文本的 CssController(确保项目目录中没有 Css 文件夹)

    控制器:

    public class CssController : Controller
    {
        [OutputCache(Duration = 6000, VaryByParam = "l")]
        public ActionResult generatecss()
        {
            return View("generatecss");
        }
    }
    

    查看:generatecss.cshtml

    @{ Layout = ""; }
    #defaultGameContainer {
            position: relative;
            width: @(SiteConfig.Instance.Game.Width + "px");
            height: 600px;
            top: 100px;
            left: 50%;
            margin-left: -480px;
        }
    

    把它作为样式表放在布局中

    <link href="~/Css/generatecss" rel="stylesheet"/>
    

    【讨论】:

    • 您好,您需要在控制器中返回正确的类型/mime 类型
    【解决方案3】:

    我相信你可以使用 LESS Css for .NET http://www.dotlesscss.org/

    【讨论】:

    • 感谢您的回复。我认为链接整个库以实现如此简单的任务几乎没有开销,因为我只有简单的 css 块,以后不打算增长。
    • @igorGIS humm.. 然后您可以使用 ajax 检索“SiteConfig.Instance.Game.Width”并使用 jquery 将其分配给您的 #defaultGameContainer: $("#defaultGameContainer").css("宽度", ajaxResult)
    • 听起来像是一个解决方案。很奇怪,我记得我们可以在页面的任何部分使用 asp.net 4 中的 语法,包括 css 块。为什么我们不能在 MVC 中
    • 因为 CSS 不是 MVC 的 Razor 引擎的注册类型,所以只能识别 cshtml。因此,您只能将 css 块放入 cshtml 页面中的
    【解决方案4】:

    谢谢你们!你建议的一切都很好! 在实验结束时,我发现它甚至可以处理那些烦人的 VS 警告。 所以我们可以在主_layout.cshtml&lt;style&gt;...&lt;/style&gt; 块中混合c# 和css 并忽略这些警告。

    【讨论】: