Controller method remains inaccessible despite multiple attempts with Javascript ajax Get call

I've tried numerous solutions for this issue, but I'm still unable to make it work. My goal is to invoke a controller method that accepts a parameter and returns a string based on that parameter. Despite using an ajax GET request, the outcome is not as expected.

Below is my controller method:

public class TestController: Controller
    {
        [HttpGet]
        public string GetString(string word)
        {
            return "Hello from Get" + word;
        }
    }

And here is my JavaScript code

testFunction();

function testFunction() {
    var word = "yay";
    $.ajax({
        type: "GET",
        url: "Test/GetString", 
        data: {word: word},
        success: function (result) {
            console.log("Success: " + result);

        },
        error: function () {
            console.log("Failed.");
        }

    });
}

Answer №1

It completely slipped my mind to do something very fundamental..

I realized I needed to include the Global.asax file with the following code snippet

public class Global : System.Web.HttpApplication
    {

        protected void Application_Start()
        {
            RouteTable.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = System.Web.Http.RouteParameter.Optional }
            );
        }

    }

After that, in my controller, all it took was changing the inherited class from Controller to ApiController along with adding the required namespace System.Web.Http

public class TestController: ApiController
    {
        public string GetString(string word)
        {
            return "Hello from Get: " + word;
        }
    }

Lastly, I made adjustments in my JavaScript by utilizing a different get function and it worked like a charm

testFunc();

    function testFunc() {
        var myword = "test";
        $.getJSON('api/test?&word='+myword,
            function (data) {

                console.log(data);

            });
    }

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

The problem with utilizing the Node `util.inherits` method

I have encountered an issue with a 'this problem' in a Node server. It seems that replacing worker.stuff with worker.stuff.bind(worker) is necessary for it to function correctly. Is there a way to incorporate the bind method into the Worker Clas ...

The NestJs project fails to display the updates when using the "tsc" command before running either "npm run start" or "npm run start:dev"

As a beginner in nestjs, I decided to start a tutorial to learn more about it. However, whenever I make updates or changes to my code, I don't see any changes reflected in the results. Can someone please assist me with this issue? Below are my tsconfi ...

Discover and modify the values of all the keys within nested JSON arrays and objects using JavaScript

I have a nested JSON data structure consisting of arrays and objects. I am looking to convert all the key values from English to Spanish using JavaScript, NodeJS, or AngularJS. { "firstrootkey" : [ //Array of 6 objects { //1st object ...

What is the best way to utilize the Stopwatch for measuring the download speed of files being downloaded?

At the beginning of form1 Stopwatch sw = new Stopwatch(); After that private void btnDownload_Click(object sender, EventArgs e) { //urll.Add("http://download.thinkbroadband.com/1GB.zip"); label7.Text = "Downloading images"; var v = lines.W ...

Oops! An unexpected field was encountered while trying to use the uploadMultiple function from dropzone.js

I was looking for a way to allow users to select images to accompany their reviews. That's when I came across dropzone.js. However, I encountered an issue when trying to send multiple images in one request. I expected the req.files to contain an arra ...

Utilizing the onscroll feature to trigger a function within a ScrollView

I am facing an issue with an animated view where I need to execute multiple events within the onScroll property. The current onScroll implementation is as follows: onScroll={ Animated.event( [{ nativeEvent: { conten ...

Can Moment.js be used to calculate the difference in years and months between two dates?

Currently, I am calculating the difference between two dates in months using this code: _result = Math.abs(moment(date1).diff(moment(date2), 'months')) + 1; This code returns an integer representing the duration in number of months. Now, I woul ...

tips for remaining in modal window post form submission

I have a form within a modal window. I am using ajax to load content in the same modal window, but the issue is that it redirects to the main page after submitting the form. How can I ensure that the modal window stays open even after the form submission? ...

Axios is passing an array instead of a JSON object when making a POST request

I am trying to make a post request using axios in my Vue.js front-end to communicate with Laravel on the backend. const data = { file: {id} } axios.post('api/documents/remove', data).then((response) => { ...

Why isn't Gzip compression working in webpack? What am I missing?

After comparing the compression results of manual webpack configuration and create-react-app for the same application, it became clear that create-react-app utilizes gzip compression, resulting in a significantly smaller final bundle size compared to manua ...

Error with replacing regular expressions in IE11 for the variable $0

Having both a string and a message: str = "Test $0 $1 $2"; message = "Hi %2 Hello %2" ; The goal is to replace all occurrences of %2 with str in the message using RegExp, like so: message = message.replace(new RegExp("%2" , "g"), str); While this works ...

What could be causing my CSS and Bootstrap.css styles not to be implemented on my webpage?

While working on my Ruby on Rails application, I am trying to customize the design to resemble (which can be downloaded from ). However, I am facing an issue where the style sheets are not being applied. I have moved the style sheets from the bootstrap/c ...

Is using $window.location.reload(true) the same as manually pressing CTRL+F5?

I'm working on developing a feature called "version updated" component that displays a banner notifying users when the website has been updated and prompts them to reload. The challenge I'm facing is that some users are experiencing issues with c ...

Several user controls are present on the page, but only the final control is being accessed

I've developed a custom UserControl that enables users to upload and view files within a GridView. The issue arises when I embed this UserControl multiple times in a jQuery tab control on the parent page. Even though the second instance functions prop ...

Connecting different jQuery methods to create a chain

From my understanding of jQuery chaining, the first method in the list must complete before the next method executes. Here is an example: $.fn.reportZebraStriper = function(options) { console.log('reportZebraStriper()'); return true; } ...

Rearranging Arrays in AngularJS: Ensuring a Specific Element Stays at the

I have exhaustively searched for an answer to my query without success. I hope that my search efforts were sufficient! Here is the issue at hand : <div id="{{expression.comment_id.$id}}" class="comments" ng-repeat="expression in expressions| orderBy:or ...

Ways to verify if an email is already registered in ASP.NET and ensure its availability prior to user registration

Is there a way to verify in an SQL Server database (not asp.net membership) whether an email is already in use before permitting the user to register? I attempted to utilize the details provided on this website, but unfortunately, it did not yield the exp ...

Jquery: Undefined Key/Value Declaration

I'm diving into the world of associative arrays for the first time and trying to access data using keys. While my array is being constructed successfully, I'm struggling to actually retrieve the data. As a result, the console.log statement at the ...

Adjust width based on value dynamically

I currently have a div that is sized at 250px, housing 3 child divs within it. My goal is for each of these 3 divs to dynamically scale based on their respective values, eventually reaching 100% width. This is the code snippet I am working with: <di ...

Encountering an "Angularjs 1.2.x Injector:modulerrr" error, even after successfully incorporating ngRoute

I am currently learning angularjs and I have encountered a persistent error. Despite multiple attempts at troubleshooting, I have been unable to resolve it. Here is the code that I have: index.html <!doctype html> <html ng-app="myApp"> <he ...