The controller did not have any corresponding action to fulfill the request sent from AngularJS connecting to Asp.Net WebApi

My mind is spinning. I am diving into the world of learning AnjularJS with Asp.Net Web Api. The following code snippet features an AnjularJS controller with an ajax call to a Web Api service.

CustomerController = function ($http, $scope, $httpParamSerializer) {
    $scope.modelObject = { first: 2, second: 3 };       
    $scope.modelObject.sendRequest = function (requestType) {
        var dataTemp = {first:2, second:3 };
        alert( $httpParamSerializer(dataTemp));
        $http({
            method: 'GET',
            url: '/api/bindings/sumnumbers',
            data: $httpParamSerializer(dataTemp),
            headers: { 'Content-Type': 'application/json' }
        }
        ).then(function successCallback(response) {
            $scope.modelObject.result = response.data;
        }, function errorCallback(response) {
            alert(response.data);
            $scope.modelObject.result = response;
        });
    }

The corresponding web api action method looks like this:

[HttpGet]
[HttpPost]
public int SumNumbers(int first, int second)
{
    return first + second;
}

I've set up a route in the webconfig for the web api as recommended in the tutorial:

config.Routes.MapHttpRoute(
    name: "Binding Example Route",
    routeTemplate: "api/{controller}/{action}/{first}/{second}"
);

However, I encounter the following error message:

{"data":{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:29845/api/bindings/sumnumbers'.","MessageDetail":"No action was found on the controller 'Bindings' that matches the request."},"status":404,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"/api/bindings/sumnumbers","data":"first=2&second=3","headers":{"Content-Type":"application/json","Accept":"application/json, text/plain, */*"}},"statusText":"Not Found"}

If anyone could offer insight into what might be causing this issue, I would greatly appreciate it.

Answer №1

If you're looking to simplify things, I suggest using Attribute Routing. Here's how you can modify your WEB API method:

[HttpGet]
[Route("api/bindings/sumnumbers/{first}/{second}")]
public int SumNumbers([FromUri] int first, [FromUri] int second)
{
    return first + second;
}

Make sure to pass the parameters in the URL within your Angular JS Controller:

url: '/api/bindings/sumnumbers/' + first + '/' + second

This should do the trick for you. Additionally, using a tool like Fiddler to test your WEB API methods before integrating them with Angular is highly recommended.

Answer №2

Recently discovered that instead of using

data: $httpParamSerializer(dataTemp),

in the AJAX call, you can just use

params: dataTemp,

In this scenario, there is no need to add a route attribute for the action method or a FromUi attribute for the parameters as suggested by keithm.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting strings into the right values through parsing

I have a JSON response that contains multiple suggestions, but I only want to parse and extract the 4 "collation" results: jQuery191029421305245357143_1380819227858( { "responseHeader": { "status": 0, "QTime": 127 }, "command": ...

Transfer data in an array within value="" separated by ':' through AJAX/JSON in PHP and HTML

Can data be passed in array form using AJAX/JSON? For example, like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."? Here is a sample code snippet to illustrate this: if(sqlsrv_num_rows($query) > 0 ...

The AJAX request is failing to send the most recent data for processing on the server side

Recently, I created a server-side processing script for datatables v1.10.0 that has been giving me some trouble. The server needs the product id to fetch records from the database, which it gets from a select2 plugin based selector selection. However, I ha ...

Can you provide a step-by-step guide on creating a JSONP Ajax request using only vanilla

// Performing an ajax request in jQuery $.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post' ,success:function (data) { console.log('ok'); }, ...

Unveiling the essence of AngularJS directives

Is there a proper way to abstract a directive in AngularJS? Consider the following basic example: http://plnkr.co/edit/h5HXEe?p=info var app = angular.module('TestApp', []); app.controller('testCtrl', function($scope) { this.save = ...

Unable to create <td> structure using nested ng-repeat loops

I am facing challenges in creating the desired table layout using nested ng-repeat. The goal is to have a table header for each day of the week and display three shifts in separate <td> elements below it. Currently, I am achieving this by placing thr ...

Can you provide some guidance on utilizing AJAX requests within a JSP environment?

I've set up a registration page using JSP and now I'm working on implementing AJAX validation. Currently, I've written a chunk of code to create a request object for AJAX. validate.js window.onload = initPage; function initPage() { ...

What is the process of retrieving user input from an HTML form and locating specific data within it?

Here is the structure of my form: <div id="employeeinfo" style="padding:40px" class="employee-body"> <form id="employeeform" title="" method="post"> <label class="title">First Name</label> < ...

Unable to change the variable for the quiz

Currently, I am in the process of developing a quiz app and I am facing an issue with my correct variable not updating. Whenever I trigger the function correctTest() by clicking on the radio button that corresponds to the correct answer, it does get execut ...

Could someone share an instance of an AngularJS configuration that continuously checks for new data and automatically refreshes the user interface once the data is obtained?

Struggling to find a suitable example for this scenario. I am looking to create a chart directive that will be updated every minute by fetching data from a web service. Currently, I have a service that acts as a wrapper for the web service. My controller ...

Having trouble retrieving JSON data using ajax

I am currently working with JSON data that is being generated by my PHP code. Here is an example of how the data looks: {"Inboxunreadmessage":4, "aaData":[{ "Inboxsubject":"Email SMTP Test", "Inboxfrom":"Deepak Saini <*****@*****.co.in>"} ...

Using highlights in an external template does not function as expected

I am new to using AngularJS and I have encountered a problem. I am currently incorporating Prism.js or Highlight.js into my website (same result). It works perfectly in index.html, but it doesn't seem to work in other templates that are loaded with n ...

Error: Attempting to retrieve request body after data stream has been read is not allowed

I am currently facing an issue where I am trying to retrieve data from AJAX in my Django post view. I have successfully created a cart with items, but now I am struggling to send the cart to the backend. Below is the JavaScript code I am using: $.ajax({ ...

Storing an array within an AngularJS service for better performance

As someone who is relatively new to AngularJS, I am still in the process of understanding how to utilize services for fetching data in my application. My aim here is to find a method to store the output of a $http.get() call that returns a JSON array. In ...

JavaScript serializer in jQuery's ajax function encountered an error while attempting to parse requested JSON data

Does anyone know how to fix a parsing error in the ajax code below? The issue arises when the service returns more than 4000 lines of data (everything works fine for fewer than 4000 lines). Any solutions? $.ajax({ url: "/service ...

Transferring data between AngularJS and non-AngularJS environments

Within my AngularJS application, the $scope.mydata variable holds some important data within a controller. I am currently working on a regular JSP page without any AngularJS functionality, but I need to access the data stored in the scope variable (mydat ...

a guide on showcasing a table according to a specific column's data (CSV Path)

I currently have a table structured like this: File Name File path MyFile1.csv D:\tmp\MyFile1.csv MyFile2.csv D:\tmp\MyFile1.csv As of now, my primary table is displayed as shown below: <div class="panel-body table-res ...

Incorporate HTML and React JS dynamically through AJAX response

Is there a way to activate React JS after inserting AJAX response into a page? The page consists of only a div and script tag as shown below; <div data-react-class="example" data-react-props="{}" data-react-cache-id="example-0& ...

Guide on changing the background color of a specific row with pagination

https://i.stack.imgur.com/Q4ggc.png Currently, I'm implementing pagination on an array and need to highlight the rows with a count of zero. The count variable in each row can be accessed using {{x.count}}. I want to customize the background color fo ...

jQuery is failing to properly render dynamic content data identifiers

Need help with a dynamic HTML div <a data-id="17" onclick="getcustomer();"> <div class="note note-success"> <h4 class="block">A</h4> <p>Email : <a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...