开发者

MVC 3 with ajax not doing ModelBinding in Controller action

开发者 https://www.devze.com 2023-02-04 14:23 出处:网络
My MVC 3 controller action is not deserializing the JSON data from my AJAX post. Fiddler shows the data being passed correctly.

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

  • Fiddler shows the data being passed correctly.
  • I put a break point on the var x = "ok!"; line and it hits it every time.
  • When the contentType is removed from the .ajax(), the address object is created but properties are null values.
  • With the contentType in the request, the address object is null.
  • I've tried to put [DataContract] and [DataMembers] on my POCO, no difference
  • I've tried to use an IModelBinder, but the StreamReader(Request.InputStream).ReadToEnd was always ""

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:

  • POST http://localhost.:59872/Settings/addressValidate HTTP/1.1
  • x-requested-with: XMLHttpRequest
  • Accept-Language: en-us
  • Referer: http://localhost.:59872/Settings/Addresses?Length=8
  • Accept: application/json, text/javascript, */*; q=0.01
  • Content-Type: application/json; charset=utf-8
  • Accept-Encoding: gzip, deflate
  • User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.2; OfficeLiveConnector.1.5; OfficeLivePatch.1.3; .NET4.0C; .NET4.0E; Creative AutoUpdate 开发者_如何学Cv1.40.01; msn OptimizedIE8;ENUS)
  • Host: localhost.:59872
  • Content-Length: 77
  • Connection: Keep-Alive
  • Pragma: no-cache
  • Cookie: __RequestVerificationToken_Lw__=IBBY7VzoqxMI .... (rest of string snipped)
  • ASP.NET_SessionId=fsjywpn4gqasszgcdgmkqd4p
  • {"Address":"1 Main Street","City":"Beach City","State":"FL","Zip":"99999"}


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

0

精彩评论

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