Can you please try this.
Student View (Razor Page)
@model IEnumerable<demo1.Models.User>
@{
ViewData["Title"] = "Student Dashboard";
}
<div id="chat">
<div id="messagesList"></div>
<input type="text" id="messageInput" placeholder="Type your message..." />
<button onclick="sendMessage()">Send</button>
</div>
@section Scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.10/signalr.min.js"></script>
<script type="text/javascript">
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.build();
connection.on("ReceiveMessage", (sender, messageContent) => {
const messageElement = document.createElement("div");
messageElement.textContent = `${sender}: ${messageContent}`;
document.getElementById("messagesList").appendChild(messageElement);
});
connection.start().catch(err => console.error(err.toString()));
function sendMessage() {
const messageContent = document.getElementById("messageInput").value;
const receiverId = "staff-id";
connection.invoke("SendMessage", receiverId, messageContent)
.catch(err => console.error('SendMessage error:', err.toString()));
}
</script>
}
Staff View (Razor Page)
You can use a similar structure for the staff view,
@model IEnumerable<demo1.Models.User>
@{
ViewData["Title"] = "Staff Dashboard";
}
<div id="chat">
<div id="messagesList"></div>
<input type="text" id="messageInput" placeholder="Type your message..." />
<button onclick="sendMessage()">Send</button>
</div>
@section Scripts {
<script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/5.0.10/signalr.min.js"></script>
<script type="text/javascript">
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.build();
connection.on("ReceiveMessage", (sender, messageContent) => {
const messageElement = document.createElement("div");
messageElement.textContent = `${sender}: ${messageContent}`;
document.getElementById("messagesList").appendChild(messageElement);
});
connection.start().catch(err => console.error(err.toString()));
function sendMessage() {
const messageContent = document.getElementById("messageInput").value;
const receiverId = "student-user-id";
connection.invoke("SendMessage", receiverId, messageContent)
.catch(err => console.error('SendMessage error:', err.toString()));
}
</script>
}
Backend SignalR Implementation
In chathub.cs class:
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;
public class chathub : Hub
{
public async Task SendMessage(string receiverId, string message)
{
await Clients.All.SendAsync("ReceiveMessage", Context.User.Identity.Name, message);
}
}