编辑 我发现我的Login.cshtml实际上引用了另一个布局页面,称为“ _LayoutAccount.cshtml”,该页面还具有@RenderSection(“ Scripts”,必填:false),并且引用Layout =“ _Layout”; 其他所有内容均保持不变。
Chrome抛出“ jquery.validate.js:15未捕获的ReferenceError:未定义jQuery”,因为我的“ _ValidationScriptsPartial”部分在jQuery和在_Layout.cshtml中定义的其他JS库之前加载。
“ _ ValidationScriptsPartial”是Login.cshtml中@Section脚本中的引用。
在我所有其他脚本之后,在_Layout.cshtml中调用“脚本”部分(@RenderSection(“ scripts”,必填:false)。
我尝试了订购/调用脚本和部分的多种组合,并用谷歌搜索过,但是所有类似的问题都有不适用于我的解决方案。
_Layout.cshtml:
...
@RenderBody()
...
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.2.0.min.js"
asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
asp-fallback-test="window.jQuery"
crossorigin="anonymous">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"
asp-fallback-src="~/lib/bootstrap/dist/js/bootstrap.min.js"
asp-fallback-test="window.jQuery && window.jQuery.fn && window.jQuery.fn.modal"
crossorigin="anonymous">
</script>
<script src="~/js/site.min.js" asp-append-version="true"></script>
</environment>
@RenderSection("Scripts", required: false)
Login.cshtml:
Layout = "_LayoutAccount";
...
@section Scripts {
@{ await Html.RenderPartialAsync("_ValidationScriptsPartial"); }
}
ValidationScriptsPartial.cshtml
<environment include="Development">
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.js"></script>
</environment>
<environment exclude="Development">
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.17.0/jquery.validate.min.js"
asp-fallback-src="~/lib/jquery-validation/dist/jquery.validate.min.js"
asp-fallback-test="window.jQuery && window.jQuery.validator"
crossorigin="anonymous">
</script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.9/jquery.validate.unobtrusive.min.js"
asp-fallback-src="~/lib/jquery-validation-unobtrusive/dist/jquery.validate.unobtrusive.min.js"
asp-fallback-test="window.jQuery && window.jQuery.validator && window.jQuery.validator.unobtrusive"
crossorigin="anonymous">
</script>
</environment>
最后,脚本按以下顺序加载:
jquery.validate.js
jquery.validate.unobtrusive.js
jquery.js
bootstrap.js
site.js
AFAIK,这不应该发生,我的Section的调用时间不正确。
答案 0 :(得分:0)
由于您在Login.cshtml中使用Layout = "_LayoutAccount";
,因此不会在Login.cshtml中加载_Layout.cshtml
的组件。您需要在_LayoutAccount.cshtml
中添加jquery:
<environment include="Development">
<script src="~/lib/jquery/dist/jquery.js"></script>
</environment>
更新:
如果在_LayoutAccount
中使用嵌套的Layout,则需要在Section中调用RenderSection()进行如下更改:
@{
Layout = "_Layout";
}
design by yourself...
@section Scripts
{
@RenderSection("scripts", required: false)
}
参考:https://asp.net-hacker.rocks/2016/02/18/extending-razor-views.html