在asp.net mvc3应用程序中加载特定于视图的样式表?

时间:2011-09-30 10:17:03

标签: asp.net-mvc-3

我正在尝试在asp.net mvc3应用程序中加载一个特定于视图的样式表(只是学习这些东西!),所以在我的_Layout.cshtml中我有:

<head>
<!--- All the common css & JS declarations here -->
@ViewBag.PageIncludes
</head>
<body>

然后在我的控制器中我有:

public ActionResult Index()
        {
            ViewBag.PageIncludes = "<link rel='stylesheet' type='text/css' href='../Content/viewspecificstylesheet.css')' />";
            return View();
        }

但是,当我查看页面时,即使声明在头部,文本也会在正文中呈现,因此呈现为文本。

结果有几个问题:

为什么,即使我在脑袋中宣称这是在体内呈现的? 为给定视图/控制器加载特定样式表的最佳实践是什么?

由于

1 个答案:

答案 0 :(得分:4)

您可以使用以下部分:

<head>
    <!--- All the common css & JS declarations here -->
    @RenderSection("Styles", false)
</head>
<body>
...
</body>

然后在Index.cshtml视图中:

@section Styles {
    <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/viewspecificstylesheet.css")" />    
}

<div>This is the index view</div>

并且您的控制器不再需要担心纯粹视图特定责任的样式:

public ActionResult Index()
{
    return View();
}
相关问题