0

SignlaR 是否自动将从客户端发送的 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;
    };
4

1 回答 1

2

您似乎正在向应用服务器发送一个 Json 字符串,而服务器正在等待一个对象。

改变:

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

到:

var jsonObject = $(this).serializeObject();
于 2013-02-10T01:19:42.900 回答