c# - 写入头部,但不是通过 _Layout.cshtml

标签 c# asp.net-mvc-3 razor

我想通过页面 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/

相关文章:

javascript - 通过 Html.BeginForm 提交激活加载动画

asp.net-mvc-3 - 如何使用 DisplayName 属性和/或 LabelFor 在表单标签中呈现 HTML 链接?

asp.net-mvc - 有没有一种方法可以在服务堆栈中缓存 Razor 页面?

c# - LINQ 中的 Where IN 子句

c# - 空引用 - 任务 ContinueWith()

asp.net - 在 ActionLink 内添加 div

asp.net-mvc-3 - MVC3页面-IsPostback之类的功能

c# - 数学运算在 C# 中无法正常工作

c# - 如何正确地将 JSON 字符串反序列化为包含另一个类的嵌套列表的类

c# - MVC3 复选框值不会清除