Friday, November 30, 2018

How to post data to MVC method using javascript fetch

There are better ways to make API calls from javascript to C# endpoints – like web api or using http handlers. But sometimes you may have a requirement to call a MVC endpoint using javascript.

Here is an example to post data to MVC endpoint and to get the return data as JSON. Make sure that you pass the correct content type


    fetch('@Url.RouteUrl(new{ action="GetResults", controller="Home"})', {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
        credentials: 'include',
        body: "token=pass-some-data"
    })
        .then(blob => blob.json())
        .then(data => {
            document.getElementById("txtResponse").value = JSON.stringify(data);
        });


Here is the complete working example; check the view and controller to see the C# and javascipt code.


No comments: