Reputation: 237
I am writing a simple Comment section using MVC and SignalR. First, the Comment View subscribes to the hub (using a "UserParticipationId" that will be used to create a group name). Then, once someone leaves a comment, the view will be sending the comment to the hub (called chathub) and the chathub will broadcast the message to all Views using the groupname.
So the two methods of my hub are:
public void subscribetogroup(int userparticipationid)
{
Groups.Add(Context.ConnectionId, userparticipationid.ToString());
}
public void broadcastnewcomment(string comment, string commenterid, int userparticipationid)
{
Comment cmt = new Comment
{
CommenterId = commenterid,
CommentDate = DateTime.Now,
UserParticipationId = userparticipationid,
CommentText = comment
};
//_commentRepository.AddCommentToUserParticipation(cmt);
Clients.Group(userparticipationid.ToString()).displaynewcomment(comment);
}
The script code in my view is:
<script>
$(function () {
var hub = $.connection.chathub;
hub.client.displaynewcomment = function (comment) {
alert(comment);
};
//hub.client.displaynewcomment = function (comment) {
// Html.RenderPartial("_CommentCardPartial", comment);
//};
$.connection.hub.start().done(function () {
hub.server.subscribetogroup(@Model.UserParticipationId);
$('#CommentButton').click(function () {
//var enteredcomment = $('#CommentText').val();
@*hub.server.broadcastnewcomment(enteredcomment, @Model.CommenterId, @Model.UserParticipationId);*@
hub.server.broadcastnewcomment("Hello", "hala", 2);
});
});
});
</script>
So my question is twofold:
If I call my hub using constants, the method call works (verified using VS debugger):
hub.server.broadcastnewcomment("Hello", "hi", 2);
However, if I use variables from my Model, the method never gets called:
hub.server.broadcastnewcomment(@Model.Comment, @Model.CommenterId, @Model.UserParticipationId);
To make it even more confusing (to me anyway), the following line always works:
hub.server.subscribetogroup(@Model.UserParticipationId);
Upvotes: 0
Views: 575
Reputation: 1326
Use single codes for string values in parameters of js function. String type values of @Model must be wrapped inside single codes like this:
hub.server.broadcastnewcomment('@Model.Comment', '@Model.CommenterId', @Model.UserParticipationId);
Upvotes: 1