سؤال

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;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top