Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Failed AJAX Post Request

I've been trying to pass an object of information to .NET Core Controller method. Passing a single string and receiving is fine. But, when I try to pass data fetched from a table, the controller is not receiving. See the code below.

Console Error Output

POST https://localhost:44366/home/GetInformation 415

MVC Controller : Tried [FromQuery] also. It gets the hit successfully but receives null.

public class HomeController : Controller
{
    [HttpPost]
    public string GetInformation([FromBody]Student student)
    {
        return "Hi " + student.Name;
    }
}

JQuery AJAX : I've tried putting Raw object, sending objects directly as data

var fetcheddata = {
    Id: col1,
    Name: col2
};

$.ajax({
    url: "home/GetInformation",
    type: "POST",
    data: JSON.stringify(fetcheddata),
    beforeSend: function (xhr) {
        xhr.setRequestHeader("RequestVerificationToken",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    success: function (data, status) {
        //task
    },
    error: function (data, status) {
        //task
    }
});

Although, using Fiddler with these params, it is working fine.

POST https://localhost:44366/home/GetInformation HTTP/1.1
User-Agent: Fiddler
Content-Type: application/json
Host: localhost:44366
Content-Length: 28

{"Id": 1, "Name":"Cucumber"}
like image 408
Ashraful Avatar asked Sep 06 '26 03:09

Ashraful


1 Answers

Try setting the Content-Type header on your AJAX request, you can see it is present in your Fiddler request.

$.ajax({
  ...
  contentType: 'application/json'
  ...
});

The default content type for jQuery.ajax() is 'application/x-www-form-urlencoded; charset=UTF-8'.

The error you're receiving is HTTP 415 - Unsupported Media Type.

like image 67
UncleDave Avatar answered Sep 07 '26 16:09

UncleDave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!