我想通过页面 View 独立写入 HTML head 元素,而不是通过 _Layout.cshtml,因为每个页面都需要不同的脚本、元数据、标题等。这可以在 ASP.NET MVC 3 中完成吗,使用 C#/Razor?
@using Test.Models;
@model IEnumerable<Player>
<!--
Put JavaScript, CSS etc... Into the page <head> here.
-->
<h2>Index</h2>
<table id="scores">
<tr>
<th>Name</th>
<th>Age</th>
<th>Gender</th>
</tr>
@foreach(Player p in Model)
{
<tr>
<td>@p.name</td>
<td>@p.age</td>
<td>@p.gender</td>
</tr>
}
</table>
<canvas id="game" width="800" height="600">
<p>Download a modern browser.</p>
</canvas>
最佳答案
您可以使用节来做到这一点。转到您的 _Layout.cshtml 并添加一个名为 head 的新部分,如下所示:
<head>
<meta charset="utf-8" />
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
@RenderSection("head", false)
</head>
新部分添加了@RenderSection。现在,在您的个人 View 中,您可以像这样向头部添加内容:
@section head
{
<script type="text/javascript">
//Your java script here
</script>
}
当呈现完整 View 时,javascript 将在链接标记正下方的 header 部分呈现。你可以把任何东西放在那里。例如,元标记。
关于c# - 写入头部,但不是通过 _Layout.cshtml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8946887/