簡體   English   中英

在部分視圖中未調用SignalR客戶端方法

[英]SignalR client-method not being called in partialview

我有一個模態彈出窗口,單擊該彈出窗口可檢索對象的局部視圖,在該對話框中,我具有另一個局部視圖,其中包含該特定對象的聊天記錄。 打開聊天功能后,它就可以正常啟動並顯示所有最新消息。 我還可以發送消息,並且看到調用了server方法來更新所有消息。 我還有另一個頁面,只有一個頁面,可以完成相同的操作(即聊天)。

但是,當我發送消息時,開放模式不會使服務器調用客戶端方法,而其他所有頁面都可以。 我不知道可能出什么問題,因此將不勝感激。 代碼如下:

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();
    }
}

用於更新和發送消息的代碼:

[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);
}

_chat局部視圖的客戶端JavaScript(其他頁面相同,除了carID = 1而不是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.");
    });
}

如果有必要,我很樂意提供更多代碼,在此先感謝互聯網人士的任何幫助!

編輯:

由於某種原因,我的其他信號發送器-hub方法之間可能沒有干擾。 但是我也使用signalr使用以下代碼來傳遞實時通知:

在我的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>

每當重大事件發生時,我都會調用eventhub.sendNotices。 所以,現在我知道問題出在哪里了,我該如何解決呢? 我可以將通知腳本放在頁面的末尾,但是在單擊時加載模態內容時,將在集線器連接啟動后打開messagehub,這使我嘗試定義方法無效。

有人知道我該怎么做嗎? 具有不同連接的多個集線器?

由於partialview是在整個站點加載后加載的,因此這意味着我試圖在集線器初始化后向SignalR添加方法,這只有在您創建了hubproxy並使用hubproxy.on(event)添加事件偵聽器的情況下才有可能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM