locked
How to Call SingnalR Client Method from Controller RRS feed

  • Question

  • User-1854646908 posted

    Hi guys,

    I want to call SignalR Hub method from AJAX Action in Controller, everything seem no problem,  but nothing happen when execute code, and no error appear,

    I put the signalr-jquery in layout page,

    that is all my code

    Layout Page:

    <html>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>@ViewBag.Title</title>
    </head>
    <body>
        @RenderBody()
    
        <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
        <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
        <script src="/signalr/hubs"></script>
    </body>
    </html>

    AJAX Action in Chat Controller:

    public class ChatController : BaseController
    {
    
            [HttpPost]
            public async Task<ActionResult> AddChat(ChatVM model)
            {
                    var context = GlobalHost.ConnectionManager.GetHubContext<ChatHub>();
                    await context.Clients.All.receiveMessage(model);
    // some code here return PartialView("_Comment", chatList); } }

    Chat Hub:

    public class ChatHub : Hub
    { 
    }

    Javascript Code in Chat page:

    var onReceive = function (obj) { 
    alert("work right");
    }
    
    window.addEventListener('load', function () {
    
            var chatHub;
            
            chatHub = $.connection.chatHub;
           chatHub.client.receiveMessage = onReceive;
            $.connection.hub.start();
    
        }, false);

    Thursday, July 18, 2019 6:13 PM

All replies

  • User283571144 posted

    Hi MrProgrammer,

    According to your description, I couldn't directly find the the reason why your view I suggest you could use F12 develop tool's to check the error message.

    If there is some error message, I suggest you could post the message. If there is not any message, I suggest you could post the details codes about the ajax view and chat view.

    Best Regards,

    Brando

    Friday, July 19, 2019 5:06 AM