asp.net-mvc - 什么是 @section 脚本及其用途

标签 asp.net-mvc

我已从 Microsoft 网站下载了一个聊天示例。我一直在关注几个教程,但在没有这 block c# 代码 (@section script{}) 的情况下完成脚本之前,我从未见过 @section script{},它似乎工作正常,但在聊天应用程序的这个实例中使用当我将脚本放在 block 之外时,发出 R 信号,它不起作用。

@section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.2.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
    $(function () {
        // Reference the auto-generated proxy for the hub.
        var chat = $.connection.chatHub;
        // Create a function that the hub can call back to display messages.
        chat.client.addNewMessageToPage = function (name, message) {
            // Add the message to the page.
            $('#discussion').append('<li><strong>' + htmlEncode(name)
                + '</strong>: ' + htmlEncode(message) + '</li>');
        };
        // Get the user name and store it to prepend to messages.
        $('#displayname').val(prompt('Enter your name:', ''));
        // Set initial focus to message input box.
        $('#message').focus();
        // Start the connection.
        $.connection.hub.start().done(function () {
            $('#sendmessage').click(function () {
                // Call the Send method on the hub.
                chat.server.send($('#displayname').val(), $('#message').val());
                // Clear text box and reset focus for next comment.
                $('#message').val('').focus();
            });
        });
    });
    // This optional function html-encodes messages for display in the page.
    function htmlEncode(value) {
        var encodedValue = $('<div />').text(value).html();
        return encodedValue;
    }
</script>
}

最佳答案

部分允许您在 View 中添加一些内容,这些内容将添加到布局中。即:-

查看

@section scripts {

    <script>

      alert('foo');

    </script>

}

布局

@RenderSection("scripts", false)

现在这个命名的部分脚本将呈现在您在布局中指定的位置。

@RenderSection 也有 2 个签名:-

public HelperResult RenderSection(string name) // section required in the view
public HelperResult RenderSection(string name, bool required)

关于asp.net-mvc - 什么是 @section 脚本及其用途,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37727972/

相关文章:

c# - Asp.net MVC 动态 Html 属性

c# - 已尝试附加或添加不是新 Linq to Sql 错误的实体

asp.net-mvc - asp.net MVC 显示模板和编辑器模板命名约定

c# - 创建Excel文件并保存时大小加倍

javascript - 如何在cshtml页面中检查ViewBag的属性?

javascript - 在 Datalist 问题中填充数据

c# - 将 json 返回到核心 2 中的部分 View

asp.net-mvc - 使用 Paypal Rest APi 时,远程服务器返回错误 : (401) Unauthorized.

jquery - ASP.NET MVC 中的条纹表行(不使用 jQuery 或等效项)

asp.net-mvc - ASP.NET MVC JsonResult 和 JQuery flot