MVC3 - '元素'链接'不能嵌套在元素'链接''中 - 尝试添加页面特定的CSS

时间:2012-05-03 15:05:09

标签: asp.net-mvc asp.net-mvc-3 razor

我有一个布局页面

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    <link href="@Url.Content("~/content/main_layout.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/content/menu.css")" rel="stylesheet" type="text/css" />
    @RenderSection("JS", required:false)
    @RenderSection("CSS", required:false)
</head>
<body>
    @RenderBody()
</body>
</html>

然后像这样的视图

@{
    ViewBag.Title = "Home";
    Layout = "~/views/shared/_layout.cshtml";
}
@using RS.Common.HtmlHelpers;
@section JS
{
    <script src="@Url.Content("~/scripts/fue.js")" type="text/javascript"></script>
    <script src="@Url.Content("~/scripts/jquery.flexslider-min.js")" type="text/javascript"></script>
}
@section CSS 
{
    <link href="@Url.Content("~/content/hp.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/content/hp_form.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/content/flexslider.css")" rel="stylesheet" type="text/css" />
}

<h4>Test!</h4>

页面加载正如我所料。但是,我收到了3个警告:

Validation (XHTML 1.0 Transitional): Element 'link' cannot be nested within element 'link'

此错误,一个用于视图中CSS部分中的每个标记。

这个阶段真的只是一个烦恼,但我想知道这个错误的原因(以及解决方案)是什么?

1 个答案:

答案 0 :(得分:9)

您已指定HTML5 DOCTYPE,但仍尝试验证为XHTML 1.0 Transitional。我想最终呈现的HTML看起来像这样:

<!DOCTYPE html>
<html>
<head>
    <title>Home</title>
    <script src="/Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
    <link href="/content/main_layout.css" rel="stylesheet" type="text/css" />
    <link href="/content/menu.css" rel="stylesheet" type="text/css" />

    <script src="/scripts/fue.js" type="text/javascript"></script>
    <script src="/scripts/jquery.flexslider-min.js" type="text/javascript"></script>

    <link href="/content/hp.css" rel="stylesheet" type="text/css" />
    <link href="/content/hp_form.css" rel="stylesheet" type="text/css" />
    <link href="/content/flexslider.css" rel="stylesheet" type="text/css" />
</head>
<body>
    <h4>Test!</h4>
</body>
</html>

您可能希望颠倒布局中两个RenderSection的顺序,以便将链接和脚本组合在一起。或者您也可以考虑将脚本声明移动到页面末尾:

像这样:

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/content/main_layout.css")" rel="stylesheet" type="text/css" />
    <link href="@Url.Content("~/content/menu.css")" rel="stylesheet" type="text/css" />
    @RenderSection("CSS", required:false)
</head>
<body>
    @RenderBody()

    <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
    @RenderSection("JS", required:false)
</body>
</html>