使用布局时如何在视图中添加脚本 src [英] how to add script src inside a View when using Layout

查看:30
本文介绍了使用布局时如何在视图中添加脚本 src的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想包含一个 javascript 参考,如:

I want to include a javascript reference like:

<script src="@Url.Content("~/Scripts/jqueryFoo.js")" type="text/javascript"></script>

如果我有一个 Razor 视图,在不必将它添加到布局的情况下包含它的正确方法是什么(我只需要在一个特定的视图中使用它,而不是所有视图)

If I have a Razor View, what is the proper way to include this without having to add it to the Layout (I only need it in a single specific View, not all of them)

在 aspx 中,我们可以使用内容占位符.我发现在 mvc 中使用 aspx 而不是 Razor 视图的旧示例..

In aspx, we could use content place holders.. I found older examples using aspx in mvc but not Razor view..

推荐答案

根据您希望如何实现它(如果您想要脚本的特定位置),您可以在其中实现一个 @section您的 _Layout 将使您能够从视图本身添加其他脚本,同时仍保留结构.例如

Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.

<!DOCTYPE html>
<html>
  <head>
    <title>...</title>
    <script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
    @RenderSection("Scripts",false/*required*/)
  </head>
  <body>
    @RenderBody()
  </body>
</html>

查看

@model MyNamespace.ViewModels.WhateverViewModel
@section Scripts
{
  <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script>
}

否则,你所拥有的一切都很好.如果您不介意它与输出的视图内联",您可以将

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆