简体   繁体   中英

How to call a hub method from c#

I'm trying to do a small signalR sample to understand it. But i got stuck and not able to get the output.

Here is my sample code

public class HubClass : Hub
{
    public void HubMethod(string myMessage)
    {
        Clients.All.hubClient(myMessage);
    }
}

public ActionResult Index()
{
    var hubContext = GlobalHost.ConnectionManager.GetHubContext<HubClass>();
    hubContext.Clients.All.HubMethod("Hello");
    return View();
}

<div class="msg"></div>
<script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script>
<script src="~/signalr/hubs"></script>
<script>
    var hubCls = $.connection.hubClass;
    $.connection.hub.start();
    hubCls.client.hubMethod = function (message) {
        $('.msg').text(message);
    };
</script>

I don't know where I'm doing wrong

In your hub you need to call the method you want invoked on the clients, ie

   Clients.All.HubMethod(myMessage);

SingalR will convert the method name to camel case and call the hubMethod function on the browser.

You also need to add an Owin startup class that enables SignalR in your site. This is described in Tutorial: Getting Started with SignalR2 and MVC 5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM