简体   繁体   中英

SignalR client-method not being called in partialview

I have a modal popup that on click retrieves a partialview for an object, inside this I have another partialview that contains a chat for this specific object. On opening the chat starts up just fine and displays all the latest messages. I can also send messages, and I see that the server method was called to update all the messages. I have another page that is just a single page, which can do the same things (ie chat).

However, when I send messages, the open modal does not get the server call to the client-method but all the other pages do. I have no idea what could be wrong so any help at all would be highly appreciated. The code is as follows:

The eventHub:

[HubName("eventHandler")]
public class eventHub : Hub
{
    private ApplicationDbContext db = new ApplicationDbContext();
    public static void SendMessages()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<eventHub>();
        context.Clients.All.updateMessages();
    }

    public static void SendNotices()
    {
        IHubContext context = GlobalHost.ConnectionManager.GetHubContext<eventHub>();
        context.Clients.All.updateNotices();
    }
}

The code for updating and sending messages:

[HttpPost]
public ActionResult SendChatMessage(string message, int chatCarID, int chatUserID)
{
    comment chatMessage = new comment() { type = commentType.chat, carID = chatCarID, userID = chatUserID, date = DateTime.Now.ToString(), text = message };
    db.comments.Add(chatMessage);
    db.SaveChanges();
    eventHub.SendMessages();
    return Content("Meddelande skickat!", "text");
}

public ActionResult GetMessages(int carID)
{
    var chatList = db.comments.Where(c => c.type == commentType.chat && c.carID == carID).ToList();
    if (chatList.Count < 1)
    {
        List<comment> emptyList = new List<comment>();
        comment emptyComment = new comment() { userID = ViewBag.serverUser.userID, writtenByUser = ViewBag.serverUser, text = "Du har inga chat-meddelanden rörande den här bilen, kolla gärna tillbaka senare!", type = commentType.chat, date = DateTime.Now.ToString() };
        emptyList.Add(emptyComment);
        return PartialView("_MessageList", emptyList);
    }
    return PartialView("_MessageList", chatList);
}

Clientside javascript for the _chat partialview (the other page is identical except for the fact that carID = 1 instead of Model.carID):

$(function () {
    $.connection.hub.enablelogging = true;
    var messages = $.connection.eventHandler;

    messages.client.updateMessages = function () {
        console.log("New messages incoming!");
        getAllChats('@Url.Action("GetMessages", "base", new { carID = Model.carID })');
    };

    $.connection.hub.start().done(function () {
        getAllChats('@Url.Action("GetMessages", "base", new { carID = Model.carID })');
    });
});

function getAllChats(get_url)
{
    var chat_holder = $('#chatMessages');
    $.ajax({
        url: get_url,
        contentType: 'application/html ; charset:utf-8',
        type: 'GET',
        dataType: 'html'
    }).success(function (result) {
        console.log("Retrieved new messages");
        chat_holder.empty().append(result);
        var messageList = document.getElementById("messageList");
        messageList.scrollTop = messageList.scrollHeight;
    }).error(function () {
        console.log("An error occured while loading the chat-messages.");
    });
}

I'd be happy to supply more of my code if that is necessary, thanks in advance for any help internet-peoples!

EDIT:

for some reason it had not occured to me that there might be interference between my other signalr-hubmethod. But I use signalr also to deliver realtime notifications, using this code:

in head of my layout.cshtml:

    <script type="text/javascript">
        $(function () {
            $.connection.hub.logging = true;
            var notices = $.connection.eventHandler;

            // Create a function that the hub can call to broadcast messages.
            notices.client.updateNotices = function () {
                console.log("Started gathering notifications");
                getAllNotices('@Url.Action("GetNotices", "base")')
            };

            // Start the connection.
            $.connection.hub.start().done(function () {
                console.log("Started gathering notifications");
                getAllNotices('@Url.Action("GetNotices", "base")');
            }).fail(function (e) {
                alert(e);
            });
        });

        function getAllNotices(get_url)
        {
            var notice_holder = $('#notifications');
            $.ajax({
                url: get_url,
                contentType: 'application/html ; charset:utf-8',
                type: 'GET',
                dataType: 'html'
            }).success(function (result) {
                notice_holder.empty().append(result);
            }).error(function () {

            });
        }
    </script>

and I call the eventhub.sendNotices every time something significant happens. So now that I know where the problem is, how do I solve it? I could put the notice-script at the end of the page but as the modal-content is loaded on click then the messagehub would be opened AFTER the hubconnection is already started, rendering my tries to define a method useless.

Does anyone have an idea of what I should do? Multiple hubs with different connections?

由于partialview是在整个站点加载后加载的,因此这意味着我试图在集线器初始化后向SignalR添加方法,这只有在您创建了hubproxy并使用hubproxy.on(event)添加事件侦听器的情况下才有可能。

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