2016-12-27 11 views
0

我正在使用MVC和SignalR編寫一個簡單的註釋部分。首先,評論視圖訂閱集線器(使用「UserParticipationId」將用於創建組名稱)。然後,一旦有人發表評論,視圖將發送評論到hub(稱爲chathub),chathub將使用groupname將消息廣播到所有視圖。使用jQuery /信號傳遞參數的問題

所以我樞紐的兩種方法是:

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> 

所以我的問題是雙重的:

  1. 如果我使用常量調用我的集線器,方法調用工作(使用VS調試器驗證):

    hub.server.broadcastnewcomment(「Hello」,「hi」,2);

不過,如果我使用變量從我的模型,該方法不會被調用:

hub.server.broadcastnewcomment(@Model.Comment, @Model.CommenterId, @Model.UserParticipationId); 

爲了使它更加混亂(我反正),下面一行始終工作:

hub.server.subscribetogroup(@Model.UserParticipationId); 
  1. 如何混合模型變量(例如@ Model.CommenterId)和我使用jquery從textarea中讀取的值。我已經評論了我的觀點,但我不確定這是否是正確的方式。
+0

我已經運行一些測試,出於某種原因,與broadcastnewcomment問題似乎當我嘗試發送字符串類型的變量出現。我只是嘗試將方法參數替換爲一堆int變量,並且調用工作。 –

回答

1

在js函數的參數中使用字符串值的單個代碼。 @Model的字符串類型的值必須用單碼內包裹這樣的:

hub.server.broadcastnewcomment('@Model.Comment', '@Model.CommenterId', @Model.UserParticipationId); 
+0

哇,非常感謝@Ankit Sahrawat。像魅力一樣工作! –

+0

雖然這可能會起作用,但我強烈建議轉義引號......如果評論是用戶可編輯的,那麼您有很大的XSS風險。 – thab