MVC 3 with ajax not doing ModelBinding in Controller action

My MVC 3 controller action is not deserializing the JSON data from my AJAX post.

Here's the jQuery code:

 $("#home-validate-btn").click(function (event) {
    var address =
    {
        Address: $('#Data_HomeAddress').val(),
        City: $('#Data_HomeCity').val(),
        State: $('#Data_HomeState').val(),
        Zip: $('#Data_HomeZip').val()
    };

    $.ajax({
        url: '/Settings/addressValidate',
        type: 'POST',
        contentType: 'application/json; charset=utf-8', 
        dataType: 'json',
        data: $.toJSON(address),            
        success: function (info) {
            alert('ok!');
        }
    });
});

Here's the controller code:

 [AcceptVerbs(HttpVerbs.Post)]         
    public ActionResult addressValidate(ValidateAddress address)
    {
        var x = "ok!";
        return new JsonResult()
        {
            Data = (x),
            JsonRequestBehavior = JsonRequestBehavior.AllowGet
        };
    }

My POCO:

public class ValidateAddress
{        
    public string Address { get; set; }        
    public string City { get; set; }        
    public string State { get; set; }   
    public string Zip { get; set; }
}

My Global.asax.cs

    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapRoute(
            "Default", // Route name
            "{controller}/{action}", // URL with parameters
            new
            {
                controller = "Home",
                action = "Index"
            } // Parameter defaults
        );
    }

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
    }

Here's the data from Fiddler:

Upvotes: 1

Views: 2005

Answers (1)

The problem was that I needed to encapsulate the return data in an object named "address" to match the method definition. I was passing an array instead of an object with properties.

New JSON =

var addressObj = {
        address: {
            Address: $('#Data_HomeAddress').val(),
            City: $('#Data_HomeCity').val(),
            State: $('#Data_HomeState').val(),
            Zip: $('#Data_HomeZip').val()
        }
    };

in the .ajax() - data: $.toJSON(addressObj),

Old JSON =

var address =
{
    Address: $('#Data_HomeAddress').val(),
    City: $('#Data_HomeCity').val(),
    State: $('#Data_HomeState').val(),
    Zip: $('#Data_HomeZip').val()
};

the old .ajax() had - data: $.toJSON(address),

http://forums.asp.net/p/1642394/4252987.aspx#4252987

Upvotes: 2

Related Questions