How I can get total number from Database by SignalR

55 Views Asked by At

i want get total employees number by signalR

but i can't doit

i add signalR on my project asp core

create Hub > dashboardHub

//////////////////////////////

Create dasjboard.js

///////////////

Create index.cshtml

//////////////

enter image description hereenter image description hereenter image description here this View

1

There are 1 best solutions below

2
Jason Pan On

UPDATE

Dashboard.cshtml

@{
    ViewData["Title"] = "Dashboard Page";
}

<div class="small-box bg-info">
    <div class="inner" id="totalEmployee">
        <h4></h4>
        @*<h3 class="text-white"></h3>*@
        <p><strong>Total Employees</strong></p>
</div>
</div>

Test Result

enter image description here

Since empTotals.Count() is of type int, we can't iterate over it with $.each().

And I also write a demo for you to send num and obj to signalr client side.

Here is the sample code

function InvokeProducts() {
    connection.invoke("EmployeeTotal").catch(function (err) {
        return console.error(err.toString());
    })
    connection.invoke("EmployeeTotalObj").catch(function (err) {
        return console.error(err.toString());
    })
}
// num
connection.on("ReceivedEmployees", function (empTotals) {
    BindProductsToGrid(empTotals);
});

function BindProductsToGrid(empTotals) {
    $("#totalEmployee h3").empty(); 

    var content = `<h2>${empTotals}</h2>`; 
    $("#totalEmployee").append(content); 
}

// obj
connection.on("ReceivedEmployeesObj", function (empTotals) {
    BindProductsToGridObj(empTotals);
});

function BindProductsToGridObj(employees) {
    //$("#totalEmployee h3").empty(); 

    $.each(employees, function (index, employee) {
        
        var content = `<h3>Name: ${employee.name} (ID: ${employee.id})</h3>`;
        $("#totalEmployee").append(content);
    });
}
connection.start().then(function () {
    InvokeProducts();
})

Hub.cs

public async Task EmployeeTotal()
{
    await Clients.All.SendAsync("ReceivedEmployees", 20);
}
public async Task EmployeeTotalObj()
{
    List<Employee> employees = new List<Employee>
    {
        new Employee { Name = "AAA", Id = 1 },
        new Employee { Name = "BBB", Id = 2 },
    };
    await Clients.All.SendAsync("ReceivedEmployeesObj", employees);
}
public class Employee
{
    public string Name { get; set; }
    public int Id { get; set; }
}

Test Result

enter image description here