Home > front end >  Jquery ui autocomplete trigger select event then ajax Post to call c# action, but it returns 400 err
Jquery ui autocomplete trigger select event then ajax Post to call c# action, but it returns 400 err

Time:08-05

My c# action looks like:

     [HttpPost]
    public JsonResult GetItems(int id)
    {
        var productsQryList = some-query-to-getitems.ToList();
        if(productsQryList != null)
        {
            return Json(productsQryList);
        } else
        {
            return Json(new());
        }
    }

In my view, the autocomplete configuration looks like:

        $("#productInfo").autocomplete({
            minLength: 1,
            source: function( request, response ) {
                $.ajax({
                    type: "GET",
                    url: "/api/purchase/SearchProductsSimple",
                    data: {
                      term: request.term
                    },
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function( data ) {
                        response( data );
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        alert(textStatus);
                    }
                });
            },
            select: function (event, ui) {
                if (ui.item) {
                    $("#order-items-table tbody tr").remove();
                    $.ajax({
                        cache: false,
                        type: "POST",
                        url: "/api/purchase/GetItems",
                        data: { "id": ui.item.value },
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            response($.map(data.d, function (itemList) {
                                for(const item of itemList) {
                                    appendOneRow(item);
                                    counter  ;
                                }
                                countTrSetIndex();
                                return false;
                            }))
                        },
                        failure: function (response) {
                            alert(response.d);
                        }
                    });
                }
            }
        });

In firefox plugin RESTED,
The GetItems method runs good if I change its attribute to HttpGet. But, if The attribute is HttpPost, I got 400 error.

By the way, The select event must be POST call.

wait for resolution. Thank you guys.

CodePudding user response:

You might have [AutoValidateAntiforgeryToken] attribute on your controller, so you must send forgery token value at ajax call.

data: { "id": ui.item.value,
"__RequestVerificationToken":$( "input[name='__RequestVerificationToken']" ).val() },
  • Related