RubbleFord
RubbleFord

Reputation: 7646

Jquery ajax post to MVC2 action

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?

Upvotes: 0

Views: 909

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039398

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

Upvotes: 2

belugabob
belugabob

Reputation: 4460

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.

Upvotes: 0

Related Questions