views:

42

answers:

2

I'm using the following script to post to and endpoint, it's hitting the breakpoint on the server so I know the routing is correct.

$(document).ready(function () {
            var o = new Object();
            o.message = 'Hi from the page';
            $.ajax({
                type: 'POST',
                contentType: 'application/json;',
                data: JSON.stringify(o),
                dataType: 'json',
                url: 'home/PingBack',
                success: function (result) {
                    alert(result.success);
                }
            });
        });

The endpoint on the server looks like this.

public JsonResult PingBack(MHolder message)
        {
            return Json(new { success = "steve"});
        }

and the Model looks like this.

  public class MHolder
    {
        public string message { get; set; }
    }

I'm sure that in the past the values have been automatically bound to the model, but I can't seem to get anything to be bound atm! Even if I just pass the value as a string, I'm sure it's something silly that I'm missing any ideas?

A: 

The code seems OK to me, at first glance.

try using...

data : {message : "Hi from the page."},

...to see if this causes the MHolder instance to be populated.

Also, use something like Fiddler to capture your requests and allow you to see exactly what is being posted.

belugabob
+2  A: 

A few things to notice. You are sending the request as a JSON string (contentType: 'application/json' and JSON.stringify(o)) while on the server you are expecting an object of type MHolder. The default model binder won't do this transformation. You will need to either write a custom model binder capable of deserializing JSON back to an MHolder instance or send the request as key=value pairs (do not stringify):

var o = new Object();
o.message = 'Hi from the page';
$.ajax({
    type: 'POST',
    data: o,
    dataType: 'json',
    url: 'home/PingBack',
    success: function (result) {
        alert(result.success);
    }
});
Darin Dimitrov