[英]How to insert scripts in an asp.net mvc c# project
When I create a default mvc asp.net c# project, on _layout.cshtml inside the body tag there is the Render.Body() and before the closing of the body there are the script bundles for jquery and bootstrap. 当我创建默认的mvc asp.net c#项目时,在body标记内的_layout.cshtml上有Render.Body(),在关闭主体之前有用于jquery和bootstrap的脚本包。 When I try to write a script in my View, it says that jQuery is not defined.
当我尝试在View中编写脚本时,它表示未定义jQuery。 That's obvious because the script bundles get called after the Render.Body().
这很明显,因为脚本包在Render.Body()之后被调用。 So I'm asking the silly question.
所以我问一个愚蠢的问题。 Is it wrong to move the bundles above the Render.Body()?
将包移动到Render.Body()上方是否错误?
You need to add a 'section' to your _Layout
file then the View can inject into it. 您需要在
_Layout
文件中添加一个“节”,然后视图才能插入其中。 This will ensure the script runs after jquery is available. 这将确保脚本在 jquery可用后运行。
Try this: 尝试这个:
Layout 布局
Add this under the jquery (and other) scripts in there: 在其中的jquery(和其他)脚本下添加以下代码:
@RenderSection("Scripts", required: false)
Views 观看次数
Then in any view you want to add some script do the following: 然后,在要添加一些脚本的任何视图中,执行以下操作:
@section scripts {
<script>
//do stuff here
</script>
}
If your dependency scripts such as jQuery are loaded after those that require them, you need to move them above. 如果像jQuery这样的依赖脚本在需要它们的脚本之后加载,则需要将它们移到上方。 You can do this, as you suggested, by moving the jQuery bundle above the body or, depending on the structure of your application, including the jQuery at the start of your script bundle.
您可以按照建议的方式将jQuery包移到正文上方,或者根据应用程序的结构(包括脚本包开头的jQuery)进行操作。
There are likely other methods to get around this problem but I have not used them. 可能还有其他方法可以解决此问题,但我没有使用过。 It is not 'wrong' to put scripts above the body, it just has different advantages and disadvantages compared to other options.
将脚本放在正文上方并不是“错误”,与其他选项相比,它具有不同的优点和缺点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.