0

Does SignlaR automatically map json object sent from to client to c# object? if so, what could i be doing wrong here?

C# Object

 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;
    };

1 Answer 1

2

You seem to be sending a Json string to the app server whereas the server is expecting an object.

Change:

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

To:

var jsonObject = $(this).serializeObject();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.