使用布局时如何在视图内添加脚本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..
根据您想要实现它的方式(如果在特定位置需要脚本),您可以在_Layout
中实现一个@section
使您可以从视图本身添加其他脚本,同时仍保留结构.例如
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>
}
否则,您所拥有的就好了.如果您不介意它与所输出的视图内联",则可以在该视图内放置<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.