I spent a couple days trying to figure out how to send data from JavaScript's Fetch() to my ASP.NET Core 5 MVC controller. For anyone else struggling for a simple easy answer on how to do this, read on.

The Why

Up till now, I have been using jQuery's implementation of AJAX to send data to the code behind. However, since Bootstrap 5, jQuery is no longer included by default in their package. Since the only thing I use jQuery for is the familiar ajax request, I wanted to find a future-proof alternative to sending and receiving data from the server. That alternative turned out to be fetch.

Lets Get Right To It

I won't bore you with the pros and cons of Fetch, or even compare fetch with other methods. You just want to know how to make it work, so lets do it.

Below is a Fetch request.  In the first line, put the path to the correct action method in your controller. I assume you are already familiar with ASP.NET Core MVC. Note that method = POST, the header content type=json. The body contains the data you want to pass to your controller.

    fetch(`/yourcontroller/youraction`, {
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
        },
        body: JSON.stringify({
            id: id,
            one: 'test'
        })
    }).then(function (response) {
        if (response.ok) {
            alert(response);
            return response.json();
        }
        return Promise.reject(response);
    }).then(data => {
        console.log('Success:', id);
    }).catch(function (error) {
        console.warn('BLAH BLAH BLAH', error);
    });

 

The controller's action method is as below. Note the FromBody tag and the Answer answer parameter. This binds the data in your Fetch body to a class named Answer that should be in your model.

        [HttpPost]
        public JsonResult YourAction([FromBody] Answer answer)
        {
            return Json(answer.id);
        }

 

The class below should be in your model.

    public class Answer
    {
        public Guid id { get; set; }
        public string one { get; set; }
    }

 

That's it! I mainly wrote this as a reminder to myself in future projects, however, I may come back to elaborate on details for future readers as well.