If I want to update a model/DB using SignalR, how is this achieved? (The other way around, i.e. from Server to Client is explained in many tutorials, but this way?)
So say we have a simple Model
public class User
{
public int UserID { get; set; }
public string UserName { get; set; }
}
And the corresponding View has an input field for the name. The hub is something like
public class UserHub : Hub
{
public void UpdateName(string value)
{
// now what?
Clients.All.updateTheViewIfNecessary(string newValue);
}
}
Edit How do I update the model, i.e. how do I achieve the same result as in the regular CRUD edit controller
db.Entry(user).State = EntityState.Modified;
db.SaveChanges();
For the purpose of this example we will use a JS client to send a model to the Hub and references official documentation at
ASP.NET SignalR Hubs API Guide - JavaScript Client: How to call server methods from the client
Assuming a User Hub on the server
public interface IUserService {
bool UpdateName(string userName);
// Other methods not shown.
}
public class UserHub : Hub {
private readonly IUserService service;
public UserHob(IUserService service) {
this.service = service;
}
public void UpdateName(string value) {
if(value != null) {
var newValue = value;
if(service.UpdateName(newValue) == true) {
Clients.All.updateTheViewIfNecessary(newValue);
}
}
}
}
Reference documentation at Dependency Injection in SignalR to understand how to inject dependencies into the hub. In the above UserHub when the message is received, it uses the data in the model to update/persist data via the injected dependency and notifies clients based on the result of that operation. This could allow for long running processes that could later update clients as needed.
A JavaScript client code that invokes the server method (assuming with the generated proxy) would look something like this.
//This assumes View has an input field for the name
var message = "Test Name";
userHubProxy.server.updateName(message).done(function () {
console.log ('Invocation of UpdateName succeeded');
}).fail(function (error) {
console.log('Invocation of UpdateName failed. Error: ' + error);
});
The framework will handle whatever model binding needs to be done on the server.
The hub in effect acts as a service endpoint and sends the response of calling the service to all clients connected to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With