Tuesday, July 11, 2017

Sending Model Data from Client to Server using SignalR

Leave a Comment

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(); 

2 Answers

Answers 1

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.

Answers 2

Call the server function to pass the values like this

         $(function () {          $("#tblData tr td").click(function (event) {                 myHub.server.sendData(userId, userName, strOtherVal)                  .fail(function (error) {                      console.log('error sending data: ' + error)                  });                        });      });

On the server side your function will look like this

 public void sendData(int userId, string userName, string strOtherVal)         {             //create model             var UserModel = new User() { UserID = userId, UserName = userName, OtherVal = strOtherVal };              //here call your function to check or post this model to db          }    public class User     {         public int UserID { get; set; }          public string UserName { get; set; }          public string OtherVal { get; set; }     } 
If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment