简体   繁体   中英

WebApi dynamic object not binding

I'm trying to send a dynamic object to an ApiController . Setting my breakpoint on the return null line, I see that the parameters is always null .

The AJAX call:

$(':checkbox').click(function (event) {
    var values = $('input[type="checkbox"]:checked').map(function () {
        return $(this).val();
    }).toArray();

    var product = {
        Name: $('#name2').val(),
        Price: $('#price2').val(),
        Category: $('#category2').val()
    };

    $.ajax({
        type: 'GET',
        url: '/api/filter',
        data: JSON.stringify( product ),
        contentType: 'application/json',

        success: function (data) {
            //alert("succeeded");
        },
        error: function (err, data) {
            alert("Error " + err.responseText);
        }
    });

});

The Controller :

[HttpGet]
public IEnumerable<Products> GetAllProducts(dynamic parameters)
{
    return null;
}

Any idea what I'm doing wrong here?

EDIT :- Changed original answer from a GET to a POST.

Assuming the code you posted is in the FilterController, the GetAll method normally does not take parameters and is used to get all the products. If you want to populate your dynamic there you should change it to a POST like so..

$.ajax({
        type: 'POST',
        url: '/api/filter/GetAllProducts,
        data: JSON.stringify( product ),
        contentType: 'application/json',

        success: function (data) {
            //alert("succeeded");
        },
        error: function (err, data) {
            alert("Error " + err.responseText);
        }
    });

then adorn you controller with the HttpPost attribute

[HttpPost]
public IEnumerable<Products> GetAllProducts(dynamic parameters)
{
    return null;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM