gpt4 book ai didi

javascript - 脚本标签中的 Razor RenderSection - 如何将脚本从 View 插入到模板函数中

转载 作者:IT王子 更新时间:2023-10-29 03:12:10 28 4
gpt4 key购买 nike

我将 MVC 3 与 Razor View 引擎一起使用,我想将来自多个 View 的脚本注入(inject)到一个集中定义的 View 中 $(document).ready();母版页中的功能。

我尝试了以下方法:

<script type="text/javascript">
$(document).ready(function () {
//OnLoad Script load area
'@RenderSection("DocumentReady", false)'
});
</script>

在我的主视图中,然后:

@section DocumentReady{
alert('Document is ready!');
}

在我看来,不出所料,由于 javascript 不在 <script> 中,我们会遇到编译错误。标签。

如果$(document).ready()中有很多小 View 控件需要运行一些初始化脚本功能,最好将它们放在一个地方。

有没有办法在没有周围 <script> 的情况下将 javascript 注入(inject)主视图?标签并且不影响编译?

最佳答案

您不需要在布局中将 RenderSection 调用用单引号引起来:

<script type="text/javascript">
$(document).ready(function () {
@RenderSection("DocumentReady", false)
});
</script>

在 View 中:

@section DocumentReady {
alert('');
}

但是如果你的布局中有一个脚本部分,它可能会更具可读性:

@RenderSection("Scripts", false)

在 View 中:

@section Scripts {
<script type="text/javascript">
$(function() {
alert('');
});
</script>
}

关于javascript - 脚本标签中的 Razor RenderSection - 如何将脚本从 View 插入到模板函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5923470/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com