I’m trying to use Ajax with JSON model binding in MVC3 RC2 and for some reason the data is not getting through to the controller action method. There have been other posts on this topic, but some refer to older versions of MVC and none of those posts that I’ve found has hit the spot. Since I’m new to JSON, JSON ModelBinding and not that well experienced in jQuery Ajax calls, I could have easily missed something.
My starting point was Scott Guthrie’s post http://bit.ly/btdFP5 introducing the MVC3 preview in the section Javascript and AJAX improvements, but I’m pulling map data off the Google API instead so my code is slightly different:
var bounds = map.getBounds();
var southWest = bounds.getSouthWest();
var northEast = bounds.getNorthEast();
var mb = { nelat: northEast.lat(), nelng: northEast.lng(), swlat: southWest.lat(), swlng: southWest.lng() };
$.ajax(
{
url: "/home/GetMarkers",
type: "post",
dataType: "json",
data:JSON.stringify(mb),
contentTYpe: "application/json; charset=utf-8",
success: function (result) {
...
The success function all works fine, so I’ve stopped the code listing there.
I have a class in the project’s domain model for the lat/long co-ordinates:
Public Class MapBounds
Public Property nelat As Double
Public Property nelng As Double
Public Property swlat As Double
Public Property swlng As Double
End Class
and the Controller action is:
Function GetMarkers(ByVal mb As MapBounds) As JsonResult
Dim objMarkers = ... get relevant data from database
Return Json(objMarkers)
End Function
The posted JSON data observed via Firebug is (typically):
{"nelat":51.22959997248028,"nelng":9.811035156249996,
"swlat":42.190280664203,"swlng":-7.8110351562500036}
but the values returned the properties in the MapBounds object are all zero. I’ve tried various variations on passing parameters including passing individual values, but with no luck. The values are either zero or null.
Phil Haack’s post – http://bit.ly/bUl21b – on sending JSON to an action method argument says that the JsonValueProviderFactory is now part of MVC3, but I checked anyway to see that it was present (and it is).
You have a typo in your contentType parameter which might prevent it from properly setting. It should be
contentTypeand notcontentTYpe.