Reputation: 275
I am writing a chat room page for my web site, and I've run into a bit of a snag. I want to be sure that the names being used by chat room participants are unique. The hub class itself contains a List<> of participants already taking part in the chat, so I added a method to the class to check for the existence of a name already in use:
public bool UserNameInUse(string name)
{
UserDetail item = ConnectedUsers.FirstOrDefault(x => x.UserName == name);
return (item.ConnectionId == null);
}
On the Javascript side, I am trying to call the hub method to check if the name is already in use before starting the connection, like so:
$("#btnStartChat").click(function () {
var name = $("#txtNickName").val();
if (name.length > 0) {
var status = chatHub.server.userNameInUse(name);
alert(status);
if (status!=1)
chatHub.server.connect(name);
else
alert("The name you chose is already in use. Try a different one, please.");
}
else {
alert("Please enter a name to use for this chat.");
}
});
As you can see, I instrumented the call to see what was being returned. But rather than obtaining a value from the hub method call (which does fire, since I tested it in Visual Studio under debug mode), this is what I get from the alert box:
I've tried changing the return type to a string and sending back text, to an int and returning a number, yet I get the same result every time when I run the code. Can anyone help me understand why the call doesn't return a value?
Upvotes: 1
Views: 1847
Reputation: 116
You need to register callback functions to receive the server response e.g.
chatHub.server.UserNameInUse(name).done(function (isInUse) {
if (isInUse) {
// Server returned true
} else {
// Server returned false
}
}).fail(function (error) {
console.log('Invocation of UserNameInUsefailed. Error: ' + error);
});
For more info check out the SignalR docs here
How to call server methods from the client
Upvotes: 2