使用布局时如何在视图中添加脚本 src

我想包含一个 javascript 引用,比如:

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

如果我有一个剃刀视图,什么是正确的方式来包含它而不必添加到布局(我只需要它在一个特定的视图,而不是所有)

在 aspx 中,我们可以使用内容占位符。.我发现在 mvc 中使用 aspx 的旧例子,但是在 Razor 视图中没有。.

227921 次浏览

取决于你想如何实现它(如果有一个特定的位置你想要的脚本) ,你可以实现一个 @section在你的 _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>

观景

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

除此之外,你拥有的一切都很好。如果您不介意它与输出的视图“内联”,那么可以将 <script>声明放在视图中。

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:

@Scripts.Render("~/bundles/jquery")
<script type="text/javascript">
$(document).ready(function () {
var divLength = $('div').length;
alert(divLength);
});
</script>

You can add the script tags like how we use in the asp.net while doing client side validations like below.

@{
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>

You should add datatable.js script on defer="defer"

<script src="https://cdn.datatables.net/1.10.8/js/jquery.dataTables.min.js" defer="defer"></script>