简体   繁体   中英

Getting a null value in IActionResult when passed with AJAX

I'm trying to make an AJAX Request to a method of iActionResult in my ASP.NET application. The request is getting to the method but when its passed along it has a value of null in my method. The value of selectedKommun is always a number when I check it in the console.

    $(document).ready(function () {

    $('#kommun').change(function () {
        var selectedKommun = $("#kommun").val();
        var fordonSelect = $('#fordon');
        fordonSelect.empty();

        if (selectedKommun != null && selectedKommun != '') {
            $.ajax({
                type: "POST",
                url: "/avboka?handler=GetFordon",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("XSRF-TOKEN",
                        $('input:hidden[name="__RequestVerificationToken"]').val());
                },
                data: { "Id": selectedKommun },
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            }).done(function (data) {
                console.log(data);
            })
            }
        });
});

Here is my method where im sending my request. I have commended out some code just to check the value of Id.

[HttpPost]
public IActionResult OnPostGetFordon(int Id)
{
    //if (!string.IsNullOrWhiteSpace(kommunFordonId) && kommunFordonId.Length == 3)
    //{

    //    IEnumerable<SelectListItem> regions = _fordonRepo.GetFordon(kommunFordonId);

    //    var json = JsonConvert.SerializeObject(regions);
    //    return this.Content(json);
    //}
    //return null;
    return new JsonResult(Id);
}

Instead of

contentType: "application/json; charset=utf-8",

try

contentType: "application/x-www-form-urlencoded; charset=UTF-8",

This is because you are not sending JSON content, only an int.

You also don't really need to specify a datatype since you are only sending an int.

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