asp.net-mvc 使用布局时如何在视图中添加脚本 src
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14284707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to add script src inside a View when using Layout
提问by dferraro
I want to include a javascript reference like:
我想包含一个 javascript 参考,如:
<script src="@Url.Content("~/Scripts/jqueryFoo.js")" type="text/javascript"></script>
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)
如果我有一个 Razor 视图,那么在不必将它添加到布局的情况下包含它的正确方法是什么(我只需要在一个特定的视图中使用它,而不是全部)
In aspx, we could use content place holders.. I found older examples using aspx in mvc but not Razor view..
在 aspx 中,我们可以使用内容占位符。我发现在 mvc 中使用 aspx 但不是 Razor 视图的旧示例。
回答by Brad Christie
Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @sectionwithin your _Layoutwhich would enable you to add additional scripts from the view itself, while still retaining structure. e.g.
根据您想要实现它的方式(如果您想要脚本的特定位置),您可以@section在您的内部实现一个,_Layout这将使您能够从视图本身添加其他脚本,同时仍保留结构。例如
_Layout
_布局
<!DOCTYPE html>
<html>
<head>
<title>...</title>
<script src="@Url.Content("~/Scripts/jquery.min.js")"></script>
@RenderSection("Scripts",false/*required*/)
</head>
<body>
@RenderBody()
</body>
</html>
View
看法
@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.
否则,你所拥有的一切都很好。如果您不介意它与输出的视图“内联”,您可以将<script>声明放在视图中。
回答by Dilip Nannaware
If you are using Razor view engine then edit the _Layout.cshtml file. Move the @Scripts.Render("~/bundles/jquery") present in footer to the header section and write the javascript / jquery code as you want:
如果您使用 Razor 视图引擎,则编辑 _Layout.cshtml 文件。将页脚中存在的 @Scripts.Render("~/bundles/jquery") 移动到标题部分,并根据需要编写 javascript / jquery 代码:
@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function () {
var divLength = $('div').length;
alert(divLength);
});
</script>
回答by Santhosh kumar Vadlamani
You can add the script tags like how we use in the asp.net while doing client side validations like below.
您可以添加脚本标签,就像我们在 asp.net 中使用的那样,同时进行如下客户端验证。
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function () {
//Your code
});
</script>

