2013-02-10 158 views
0

SignlaR是否自動將從客戶端發送的json對象映射到c#對象?如果是這樣,我會在這裏做錯什麼?SingalR將json對象映射到c#對象

C#對象

public class ChatHub :Hub 
    { 
     public void broadcastMessage(CommentModel model) 
     { 
      string test = model.Comment; 
      // Clients.All.writeMessage(jsonString); 
     } 


     public class CommentModel 
     { 
      [Required] 
      public string Name { get; set; } 

      [Required] 
      public string Comment { get; set; } 

      [Required] 
      public string EmailAddress { get; set; } 
     } 
    } 

的JavaScript

$(document).ready(function() { 

     var chat = $.connection.chatHub; 
     chat.client.writeMessage = function (t) { 
      var name = t.Name; 
      var email = t.Email; 
      var id = t.id; 
      var text = name + " " + email + " " + id + " "; 
      $("#test").append(text); 
     } 

     $("form").submit(function (e) { 

      var jsonObject = JSON.stringify($(this).serializeObject()); 
      chat.server.broadcastMessage(jsonObject); 
      e.preventDefault(); 
     }); 

     $.connection.hub.start(); 
    }); 

    $.fn.serializeObject = function() { 
     var o = {}; 
     var a = this.serializeArray(); 
     $.each(a, function() { 
      if (o[this.name] !== undefined) { 
       if (!o[this.name].push) { 
        o[this.name] = [o[this.name]]; 
       } 
       o[this.name].push(this.value || ''); 
      } else { 
       o[this.name] = this.value || ''; 
      } 
     }); 
     return o; 
    }; 

回答

2

你似乎是發送一個JSON字符串到應用程序服務器,而服務器期待的對象。

變化:

var jsonObject = JSON.stringify($(this).serializeObject()); 

要:

var jsonObject = $(this).serializeObject();