如何在ASP.Net MVC应用程序

时间:2017-09-23 14:19:32

标签: javascript asp.net-mvc

我是MVC / .net的新手,目前正在做一些简单的练习。我有这个javascript代码,我尝试注册我的服务工作者但由于某种原因,它没有运行。我按照我能找到的所有教程进行了搜索,但是仍然没有找到它。所以我迷失在这里。谢谢你的帮助。

@RenderSection("pageScripts", required: false)
@section pageScripts{
    <script type="text/javascript" language="javascript">

        console.log('test script');

        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/service-worker.js').
                then(function (registration) {
                    // Registration was successful
                    console.log('ServiceWorker registration successful with scope: ', registration.scope);
                }).catch(function (err) {
                    // registration failed :(
                    console.log('ServiceWorker registration failed: ', err);
                });
        }

    </script>
}

1 个答案:

答案 0 :(得分:2)

假设LayOut文件需要您编写的脚本逻辑,则需要使用以下代码替换代码:

<script type="text/javascript" language="javascript">

            console.log('test script');

            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.register('/service-worker.js').
                    then(function (registration) {
                        // Registration was successful
                        console.log('ServiceWorker registration successful with scope: ', registration.scope);
                    }).catch(function (err) {
                        // registration failed :(
                        console.log('ServiceWorker registration failed: ', err);
                    });
            }

        </script>
    @RenderSection("pageScripts", required: false) // NOTICE IT HAS COME DOWN

请注意:如果您在布局文件中,那么您不需要添加

@section pageScripts{
}

在旁注中,在布局文件

中添加脚本的顺序
    ....   
    ....
   </div>
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("Any Third Party Script") 
    @Scripts.Render("Your own Custom Script file Required By Entire Application")
    <script>
       // ADD ANY Script related to LayOut Page here
        </script>
     @RenderSection("pageScripts", required: false)
</body>
</html>

现在,如果特定视图专门需要脚本,那么..

例如:Index.csthml

...
</div>

@section pageScripts
{
  // Your script logic
}