信号器聊天记录用户名

时间:2015-11-29 13:55:51

标签: jquery asp.net-mvc signalr signalr-hub

您好我正在尝试将记录的会员名称发送到信号聊天这里是我的索引

<script>
    $(function () {
        var currentMember= @Html.Raw(@ViewBag.Name);
        // 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>

而不是这一行

 $('#displayname').val(prompt('Enter your name:', ''));

我试过这些

$('#displayname').val("@HttpContext.Current.User.Identity.Name");
 $('#displayname').val(currentMember);

但这些都没有用。那么如何才能获得我记录的会员姓名?

1 个答案:

答案 0 :(得分:0)

看看这一行

var currentMember= @Html.Raw(@ViewBag.Name);

假设ViewBag.Name正在返回字符串furkan。如果您检查页面的查看源,您将看到

var currentMember = furkan;

Javascript会认为furkan是一个变量,但它不是!

解决方案:用双引号或单引号

包装服务器代码
var currentMember= '@Html.Raw(@ViewBag.Name)';

现在,如果您检查页面的查看源,它将是

var currentMember = 'furkan';

所以现在currentMember变量存储一个字符串值。您可以稍后在代码中使用它。

var currentMember= '@Html.Raw(@ViewBag.Name)';
alert(currentMember);
$('#displayname').val(currentMember);