Answer the question
In order to leave comments, you need to log in
Why is SignalR in asp.net c# with js client not working?
I did a similar thing in another project, it worked great. The bottom line: when you go to the MyData page, data is sent to the js client, it should display them
Now I have done everything according to this article https://metanit.com/sharp/aspnet5/30.6.php , I understand that everything should work, but no. There are no errors, the hub connection with the js client is established without problems, but no data is displayed.
controller
public class HomeController : Controller
{
private ApplicationDbContext _db;
private IHubContext<MoexHub> _hub;
public HomeController(ApplicationDbContext db, IHubContext<MoexHub> hub)
{
_db = db;
_hub = hub;
}
public IActionResult Index()
{
return View();
}
public async Task<IActionResult> MyData()
{
await _hub.Clients.All.SendAsync("notify", "this is my message");
return View();
}
}
const hubConnection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.build();
// получение сообщения от сервера
hubConnection.on('notify', function (message) {
// создает элемент <p> для сообщения пользователя
let elem = document.createElement("p");
elem.appendChild(document.createTextNode(message));
document.getElementById("notify").appendChild(elem);
console.log(message);
});
hubConnection.start();
<div id="notify"></div>
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/signalr/dist/browser/signalr.min.js"></script>
<script src="~/js/LoadData.js"></script>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>
Answer the question
In order to leave comments, you need to log in
The event name is case sensitive.
On the C# side you send "Notify" and on the js side you subscribe to "notify".
Change so that it matches on both sides.
Of course, there are no errors, because signalr does not know anything about what events the back and front can send.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question