Click here to Skip to main content
16,022,236 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I have made a chat box when I enter message and click on send the message does not send to the other browser

What I have tried:

Student VIEW
Razor
@model IEnumerable<demo1.models.user>
@{
    ViewData["Title"] = "Dashboard";
}
    <title>Student Dashboard
    
    <div id="chat">
        <div id="messagesList"></div>
        
        Send
    </div>

        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-user-id"; // Get this from the context or your application logic

            connection.invoke("SendMessage", receiverId, messageContent)
                .catch(err => console.error('SendMessage error:', err.toString()));
        }

The same code in staff view

Program.cs file code:
C#
using demo1.Models;
using Demo1.Hubs;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddSignalR();
//DB Connection
builder.Services.AddDbContext<projectcontext>(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("constring")));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapControllerRoute(
        name: "default",
        pattern: "{controller=Test}/{action=Login}/{id?}");

app.MapHub<chathub>("/chathub");

app.Run();
Posted
Updated 4-Sep-24 1:33am
v2

1 solution

Can you please try this.

Student View (Razor Page)
C#
@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,

C#
@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"; // Replace with the actual logic to identify the student

            connection.invoke("SendMessage", receiverId, messageContent)
                .catch(err => console.error('SendMessage error:', err.toString()));
        }
    </script>
}


Backend SignalR Implementation
In chathub.cs class:

C#
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);
    }
}
 
Share this answer
 
v4
Comments
Dave Kreskowiak 4-Sep-24 9:10am    
Don't someone's homework for them is frowned upon here.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900