开发者

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(resu开发者_开发问答lt.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 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);
    }
});


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜