使用布局时如何在视图中添加脚本 src [英] how to add script src inside a View when using Layout
问题描述
我想包含一个 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>
}
否则,你所拥有的一切都很好.如果您不介意它与输出的视图内联",您可以将 声明放在视图中.
Otherwise, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script>
declaration within the view.
这篇关于使用布局时如何在视图中添加脚本 src的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!