Sreenath Ganga
Sreenath Ganga

Reputation: 736

Calling SignalR Hub method from code behind

I had a web Application with master page and I need to show a alert to all connected users of my application. I had used the Owin startup class and mapped signal R

Then created a Hub like below

    namespace ArtWebApp
{
    [HubName("artHub")]
    public class ArtWebHub : Hub
    {

        public void Hello()
        {
            Clients.All.hello();
        }


        public void SayMessage()
        {
            this.Clients.All.showmessage();

        }
    }
}

Then in the masterpage I added the Javascript as below

 <script src="Scripts/jquery-1.6.4.js"></script>
    <script src="Scripts/jquery.signalR-2.2.1.js"></script>
    <script type="text/javascript">
        $(function () {
            debugger;
            var connection = $.hubConnection("")
            var hub = connection.createHubProxy('artHub');
            hub.on('showmessage', function () {

                alert('Hi');
            });


            connection.start().done();
            //connection.start(function () {

            //    hub.invoke('SayMessage');
            //});
        });

    </script>

This is working perfectly when the Hub method is invoked from the same page but when I tried to call the method from button click of a page its not working

  protected void Button1_Click(object sender, EventArgs e)
    {            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ArtWebApp.ArtWebHub>();
        hubContext.Clients.All.SayMessage();    
    }

Can somebody suggest me the issue

Upvotes: 5

Views: 4455

Answers (1)

scartag
scartag

Reputation: 17680

What i can see from your code is a mistake on the client side function you are calling.

Clients.All typically lets you invoke a function you have defined at the client side by calling Clients.All.functionName()

In the Button1_Click event please change

 hubContext.Clients.All.SayMessage(); 

To

 hubContext.Clients.All.showMessage(); 

This is because you are using the dynamic collection Clients

You are trying to invoke a client side function (which doesn't exist).

The method SayMessage you are trying to call is a member of the ArtWebHub class and cannot be invoked by calling hubContext.Clients.All.

You can invoke SayMessage from the client using hub.invoke('SayMessage') but to invoke the showmessage function defined in the client you'll have to invoke it differently from the server because SayMessage is not available to the hubContext

Upvotes: 5

Related Questions