C# MVC - Send message with SignalR from server to

2019-09-05 16:36发布

问题:

I have a request from client to Server using SignalR-2.2.1. After that request, Server will send the results back to the caller. Here is my JavaScript code :

$(document).ready(function () {
    var myHub = $.connection.signalHub;
    myHub.client.receive = function (tmp) {
        var obj = $.parseJSON(tmp);
        //do something
    };
    $.connection.hub.start().done(function () {
        $('#xxxxx').click(function () {
            var form = $("form");
            form.submit();
            myHub.server.sendSomething();
        });
    }).fail(function (reason) {
       //do something
    });
});

And here is the code from my Server Side

public partial class SignalHub : Hub
{
    public void SendSomething()
    {
         Clients.All.receive(MyJson);
    }
}

When I use Clients.All function, it works perfectly fine. But what I want is the server only send the result back to the caller (the one that send the request). So I change Clients.All.receive(MyJson) to Clients.Caller.receive(MyJson). After I change it, now the client doesnt update the content. Do I need to specify my receive function in client side that it would receive something different?

回答1:

My guess is that since you are calling form.submit(); you are probably navigating away from the page or possibly reloading it, in that sense a new connection with a different "connectionId" is established between the new/reloaded page, thus the message intended for Client.Caller is lost since it is associated with the connection established on the page that you navigated away from or refreshed.

You might want to consider posting your form-data using AJAX instead of a full form submit.