I'm new in asp.net core
I created a post method in the controller ([HttpPost]) and after posting , I created a view that shows all the records. is there an easy way to play a sound when a new record is posted ?
CodePudding user response:
You can use SignalR to push real-time notifications in your list view. It allows server code to send asynchronous notifications to client-side web applications. Basically, the idea is after inserting a new record into DB you will push a message using SignalR and it'll reflect in the client panel immediately.
Here is the example:
Notification Hub
public class NotificationHub : Hub
{
}
Add it in Startup
public class Startup
{
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapHub<NotificationHub>("/notfHub"); // <====== add this ======
});
}
}
In client side (notification.js)
"use strict";
var connection = new signalR.HubConnectionBuilder().withUrl("/notfHub").build();
connection.on("sendNotification", (data) => {
alert(data)
});
connection.start().catch(function (err) {
return console.error(err.toString());
});
So when you insert new entity you can send new notification after insertion and it'll be pushed in the client side.
public class AdminController : Controller
{
private readonly IHubContext<NotificationHub> _notificationHubContext;
public AdminController(IHubContext<NotificationHub> notificationHubContext)
{
_notificationHubContext = notificationHubContext;
}
[HttpPost]
public async Task<IActionResult> Add(User model)
{
// add your db insertion operation here
await _notificationHubContext.Clients.All.SendAsync("sendNotification", model);
return View();
}
}