Search code examples
jqueryasp.net-mvcsignalrsignalr-hub

Signalr Chat logged User Name


Hello I am trying to get logged member name to signalr chat here is my Index

<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>

instead of this line

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

I tried these

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

but these didnt work. So how can I get my logged member Name ?


Solution

  • Take a look at this line

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

    Assume ViewBag.Name is returning the string furkan. If you check the view source of the page, you will see

    var currentMember = furkan;
    

    Javascript is going to think that furkan is a variable, but it is not!

    Solution : Wrap your server code with double quotes or single quotes

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

    Now if you check view source of the page, It will be

    var currentMember = 'furkan';
    

    So now currentMember variable stores a string value. You can use it in your code later.

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