SignalR聊天:区分CSS的ListItem发送者和接收者

时间:2018-12-17 19:51:07

标签: javascript css asp.net-core-mvc signalr chat

我正在基于Microsoft的SignalR和JavaScript教程构建一个小型ChatHub应用程序。

简而言之:集线器消息放入按需创建(li)

出于样式目的,我正在为这些(li)添加一个类名,将它们区分为“发送者”和“接收者”类别

背景: ChatConnection的每一侧都有不同的视图。我仍在建立发短信的逻辑,因此这绝不是完美的事情。

我给Friendstable的dbo是UserFriends,取决于您处于友谊的哪一侧,您会获得一个不同的(但镜像的)聊天窗口。

Cshtml代码段:

     @foreach (var item in Model.UserFriends)
        {
            @if (item.FriendChatName == @User.Identity.Name)
            {

                <div>
                    <button class="open-button" onclick="openChatForm()">@item.UserChatName</button>
                    <div class="chat-popup" id="myChatForm" style="display:none">
                        <form action="/action_page.php" class="form-container">
                            <button type="button" class="btn cancel" onclick="closeChatForm()">@item.UserChatName</button>
                           <input type="hidden" id="receiverInput" value="@item.UserChatName"/>
                                <ul id="messagesList" class="chatmessage receiver" ></ul>


                            <input type="hidden" id="userInput" class="receiverInput" value="@item.FriendChatName" />
                            <textarea placeholder="Type message.." required style="height:32px;" id="messageInput"></textarea>
                            <button type="submit" asp-route-user="@User.Identity.Name" asp-route-sender="@User.Identity.Name" asp-route-receiver="@item.UserChatName" class="btn" id="sendButton">Send</button>
                        </form>
                    </div>
                </div>


            }
            @if (item.UserChatName == @User.Identity.Name)
            {
                <div>
                    <button class="open-button" onclick="openChatForm()">@item.FriendChatName</button>
                    <div class="chat-popup" id="myChatForm" style="display:none">
                        <form action="/action_page.php" class="form-container">
                            <button type="button" class="btn cancel" onclick="closeChatForm()">@item.FriendChatName</button>
                            <input type="hidden" id="receiverInput" value="@item.FriendChatName" />
                            <ul id="messagesList" class="chatmessage sender" ></ul>

                            <input type="hidden" id="userInput" value="@item.UserChatName" />
                            <textarea placeholder="Type message.." required style="height:32px;" id="messageInput"></textarea>
                            <button type="submit" asp-area="" asp-route-user="@User.Identity.Name" asp-route-sender="@User.Identity.Name" asp-route-receiver="@item.FriendChatName" class="btn" id="sendButton">Send</button>
                        </form>
                    </div>
                </div>
            }
        }

ChatHub类:

       public class ChatHub : Hub
{
    public async Task SendMessage(string user, string message)
    {
        await Clients.All.SendAsync("ReceiveMessage", user, message);
    }
}

和chat.js脚本片段:

    var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
     connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
var encodedMsg = user + ": " + msg;
var li = document.createElement("li");    
li.textContent = encodedMsg;    
document.getElementById("messagesList").appendChild(li);
    });
    connection.start().catch(function (err) {
return console.error(err.toString());
    });
    document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;


connection.invoke("SendMessage", user, message).catch(function (err) {
    return console.error(err.toString());
});
event.preventDefault();
    });

我正在尝试得到这种东西:

        if (user == reciever  ) {
    li.className = "receiver";
}
if (user == sender) {
    li.className = "sender";
}

借助此代码段

    var sender = document.getElementById("senderInput").value;
var receiver = document.getElementById("receiverInput").value;

但是当一切顺利之后,除了运行时错误我什么都没有

Error

这是两个浏览器窗口中的视图

ChatView in two browser windows

任何人都可以在chat.Js中帮助我构建If,或者有其他关于我如何以不同方式设置发送方消息和接收方消息样式的结构性注释,将不胜感激!

1 个答案:

答案 0 :(得分:1)

我将针对该问题发布解决方案:

     @foreach (var item in Model.User.Friends)
            {
                <li>
                    <button class="open-button" onclick="openChatForm(event, '@item.Id@@ChatForm')" type="button" style="max-width:200px;">@item.UserName</button>
                    <div class="chat-popup" id="@item.Id@@ChatForm" style="display:none; width:300px; margin-left:900px;">
                        <div>
                            <form action="/action_page.php" class="form-container" style="position:absolute">
                                <button class="btn cancel" onclick="closeChatForm(event, '@item.Id@@ChatForm')" type="button">@item.FirstName</button>
                                <input type="hidden" id="receiverInput" value="@item.UserName" />
                                <ul id="messagesList" class="chatmessage" style="max-height:600px;"></ul>
                                <input type="hidden" id="senderInput" value="@User.Identity.Name" />
                                <textarea placeholder="Type message.." required style="height:32px;" id="messageInput"></textarea>
                                <button type="submit" class="btn" id="sendButton">Send</button>
                            </form>
                        </div>
                    </div>
                    <script>

                    </script>

                </li>
            }

这是chat.js

    connection.on("ReceiveMessage", function (user, message) {
var msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
var encodedMsg = user + ": " + msg;

var li = document.createElement("li");
li.className += user;

var senderForSenderForm = document.getElementById("senderInput").value;
var senderForReceiverForm = document.getElementById("receiverInput").value;
var receiverForSenderForm = document.getElementById("receiverInput").value;
var receiverForReceiverForm = document.getElementById("senderInput").value;

if (senderForSenderForm === li.className ) {
    li.className += " toRight";
}
if (receiverForSenderForm === li.className) {
    li.className += " toLeft";
}
if (senderForReceiverForm === li.className ) {
    li.className += " toRight";
}
if (receiverForReceiverForm === li.className) {
 li.className += " toLeft";
}

li.textContent = encodedMsg;
document.getElementById("messagesList").appendChild(li);

    });

    connection.start().catch(function (err) {
return console.error(err.toString());
    });

    document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("senderInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("SendMessage", user, message).catch(function (err) {
    return console.error(err.toString());
});
event.preventDefault();
    });

ChatHub还是一样。

简而言之,我将聊天窗口重构为一个范围, 生成(li)消息,并向其添加一个类,以最终根据该className设置样式。

可以为所有朋友设置样式,可以与一个朋友聊天atm,并且在修复后会更新!

dogFaceChat