我正在使用MVC和SignalR编写一个简单的评论部分。首先,注释视图订阅了集线器(使用将用于创建组名称的" userparticipationId")。然后,一旦有人发表评论,该视图将向集线器发送评论(称为Chathub),Chathub将使用GroupName将消息传播到所有视图。
所以我的轮毂的两种方法是:
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);
}
我认为的脚本代码是:
<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>
所以我的问题是双重的:
如果我使用常数调用我的集线器,则该方法调用有效(使用vs debugger进行了验证):
hub.server.broadcastnewcomment(" Hello"," Hi",2);
但是,如果我使用模型中的变量,则该方法永远不会被调用:
hub.server.broadcastnewcomment(@Model.Comment, @Model.CommenterId, @Model.UserParticipationId);
使其更加令人困惑(无论如何对我来说),以下行总是有效:
hub.server.subscribetogroup(@Model.UserParticipationId);
- 如何混合模型变量(例如 @model.commenterid)和我使用jQuery从Textarea读取的值。我已经评论了我认为有什么,但是我不确定这是否是正确的方法。
在JS函数的参数中使用单个代码对字符串值。@model的字符串类型值必须包装在单个代码中:
hub.server.broadcastnewcomment('@Model.Comment', '@Model.CommenterId', @Model.UserParticipationId);