我已从 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/