Signal r notification

2019-08-31 00:43发布

I am creating an application using signal r to send notification. I am using VS 2012. In my Notification view I have added the code below in @model App.Models.Notification.

@{
    ViewBag.Title = "Index";
}

@section Scripts
{    
    <script src="/Scripts/jquery-1.8.20.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.2.0.js"></script>
    <script src="/signalr/hubs"></script>

    <script type="text/javascript">
        $(function () {

            var proxy = $.connection.notificationHub;
            alert(proxy);
            $("#button1").click(function () {
                alert($("#text1").val());
                proxy.server.sendNotifications($("#text1").val());
                alert(12);
            });
            $.connection.hub.start();

            alert(14);
        });
    </script>
}
<h2>Index</h2>

@using (Html.BeginForm())
{
    <input id="text1" type="text" />
    <input id="button1" type="submit" value="Send" />
}

On click of the button, sendNotifications() is not getting called and the notification is not sending to client.

This is the hub class

public class NotificationHub : Hub
{
    public void Hello()
    {
        Clients.All.hello();
    }

    public void SendNotifications(string message)
    {
        Clients.All.receiveNotification(message);
    }
}

Can someone help me with a solution

1条回答
▲ chillily
2楼-- · 2019-08-31 01:25

You also need to create a owin startup class. I will put code here for that (view same as your) :-

<script src="~/Scripts/jquery-1.10.2.min.js"></script>
    <script src="~/Scripts/jquery.signalR-2.1.2.min.js"></script>
    <script src="/signalr/hubs"></script>

    <script type="text/javascript">
        $(function () {

            var proxy = $.connection.notificationHub;
            alert(proxy);
            $("#button1").click(function () {
                alert($("#text1").val());
                proxy.server.sendNotifications($("#text1").val());
                alert(12);
            });
            $.connection.hub.start();

            alert(14);
        });
    </script>

Notification Hub like :

public class NotificationHub : Hub
{
    public void Hello()
    {
        Clients.All.hello();
    }

    public void SendNotifications(string message)
    {
        Clients.All.receiveNotification(message);
    }
}

Now Most importnant you need to create a owin startup class to start signal r, code like :

    public void Configuration(IAppBuilder app)
    {
        app.MapSignalR();
    }
查看更多
登录 后发表回答