Web API complex parameter properties are all null

前端 未结 18 1538
长情又很酷
长情又很酷 2020-11-30 04:18

I have a Web API service call that updates a user\'s preferences. Unfortunately when I call this POST method from a jQuery ajax call, the request parameter object\'s proper

18条回答
  •  佛祖请我去吃肉
    2020-11-30 05:11

    A bit late to the party, but I had this same issue and the fix was declaring the contentType in your ajax call:

        var settings = {
            HelpText: $('#help-text').val(),
            BranchId: $("#branch-select").val(),
            Department: $('input[name=departmentRadios]:checked').val()
    
        };
    
    $.ajax({
            url: 'http://localhost:25131/api/test/updatesettings',
            type: 'POST',
            data: JSON.stringify(settings),
            contentType: "application/json;charset=utf-8",
            success: function (data) {
                alert('Success');
            },
            error: function (x, y, z) {
                alert(x + '\n' + y + '\n' + z);
            }
        });
    

    And your API controller can be set up like this:

        [System.Web.Http.HttpPost]
        public IHttpActionResult UpdateSettings([FromBody()] UserSettings settings)
        {
    //do stuff with your UserSettings object now
            return Ok("Successfully updated settings");
        }
    

提交回复
热议问题