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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5923470/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 19:32:03  来源:igfitidea点击:

Razor RenderSection within script tags - How to insert script from view into template function

javascriptasp.net-mvc-3razor

提问by Oliver

I'm using MVC 3 with the Razor view engine and I would like to inject scripts from multiple views into one centrally defined $(document).ready();function in the master page.

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

I have tried the following:

我尝试了以下方法:

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

In my master view, and then:

在我的主人看来,然后:

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

In my view, but unsuprisingly, we get compilation errors due to the javascript not being within a <script>tag.

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

If there are a lot of small view controls that need to run some initialisation script in the $(document).ready()function, it would be nice to keep them all together in a single place.

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

Is there a way to inject javascript to a master view without the surrounding <script>tags and without affecting compilation?

有没有办法将 javascript 注入主视图而没有周围的<script>标签并且不影响编译?

回答by Darin Dimitrov

You don't need the single quotes around the RenderSection call in your layout:

您不需要在布局中的 RenderSection 调用周围使用单引号:

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

and inside the view:

并在视图内:

@section DocumentReady {
    alert('');
}

But it will probably be more readable if you have a scripts section in your layout:

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

@RenderSection("Scripts", false)

and inside the view:

并在视图内:

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

回答by Ema.H

For example, in your _layout.cshtml :

例如,在您的 _layout.cshtml 中:

@RenderSection("JavaScript", required: false)

And then in your view :

然后在您看来:

    @section JavaScript
    {
       <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
       <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>

       <script type="text/javascript">console.log("in the js");</script>
    }

Hope that helps

希望有帮助