Having trouble retrieving list data in JSON response while utilizing the ASP.NET Web API in MVC

In my Project, this is the JavaScript code:

function RetrieveData() {
                debugger;
                var url = 'http://localhost:50951/api/Home';
                $.ajax({
                    type: "GET",
                    url: url,
                    dataType: "json",
                    success: function (data) {
                        alert("Retrieve Successful");
                    },
                    error: function (error) {
                        alert("Error Retrieving Data");
                    }
                });
        }

This is the corresponding WebApi code:

public class HomeController : ApiController
            {
                public IEnumerable<KeyValuePair<string, string>> Index()
                {
                    List<KeyValuePair<string, string>> listString = new List<KeyValuePair<string, string>>()
                    {
                        new KeyValuePair<string, string> ("India","India"),
                        new KeyValuePair<string, string> ("Australia","Australia"),
                    };
                    return listString;
                }
            }

When trying to call the RetrieveData function, it triggers the API but shows an error message in JavaScript. It does not enter the success block. Is there a way to receive the list data in JSON response when using the API?

Answer №1

If you are using the Get method, make sure there is a corresponding Get method in the web api. You can either rename the Index() as Get(), or add a [HttpGet] attribute before the Index() method to indicate it's a GET request, like this:

public class HomeController : ApiController
       {
          [HttpGet]
          [Route("api/Home")]
          public List<KeyValuePair<string, string>> Index()
          {
              List<KeyValuePair<string, string>> listString = new List<KeyValuePair<string, string>>()
              {
                  new KeyValuePair<string, string> ("India","India"),
                  new KeyValuePair<string, string> ("Australia","Australia"),
              };
              return listString;
           }
       }

Ensure that the URL is set up correctly:

var url = '/api/Home';

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

Seeking a POST request to a specific URL

Hey there! I'm currently working on developing an Airtime application and need some guidance. Here's what I need help with: To send airtime, I have to make a HTTP POST request to one of the following endpoints: Live: Sandbox: These are the req ...

Error retrieving Facebook access token using Node.js https.get()

I've been working on setting up a Facebook login flow in my node.js app, but I'm facing an issue where the access token isn't returning from the Facebook API when using node's https.get() method. Interestingly, I am able to retrieve the ...

the append function combines existing data with new data

After retrieving data through ajax, I am facing a challenge in displaying it within a UI popup: [{"BadgeImage":"http:\/\/localhost:8666\/web1\/profile\/images\/badge image 2\/1.png"}, {"BadgeImage":"http:\/\/lo ...

Delay the HTTPs request until the password encryption is complete

Hey there! I'm working on a post request where I need to collect login data (name, email, password) from users, validate it, encrypt the password, and then store the data. However, I'm facing an issue with the encryption function taking time to r ...

Querying MongoDB using a generic search method in the Repository

I'm currently working on creating a generic repository with a find operation that accepts an expression. Here's what I have so far, using FastMapper for projecting from entity objects to external contract objects: public override List<T&g ...

Learn how to render a dynamic checkbox that is connected with AJAX and PHP for seamless functionality

I need to showcase a dynamic checkbox that can be bound using ajax and php. Here is my code: <?php include 'dbconnect.php'; $result = mysqli_query($link, "SELECT * FROM city where district_id='$dist' "); while($city_row=mysqli_fe ...

Is it possible for Express.Js to generate minified JSON output?

As I make the transition from restified to Express, one thing I've noticed is that the JSON output of res.send({}) in Express is nicely formatted with white space, while Restify produces minified JSON without any extra spacing. Even though this JSON ...

A guide on converting character objects to strings

Presented below is an array of characters: Resource {0: "-", 1: "-", 2: "-", 3: "-", 4: "-", 5: "B", 6: "E", 7: "G", 8: "I", 9: "N", 10: " ", 11: "C", 12: "E", 13: "R", 14: "T", 15: "I", .... } I am looking to convert it into the following format: --- ...

JSON appears to be failing to be identified

I am encountering difficulties in getting my JSON data to display correctly on my web page. Even though I have validated the JSON returned from the server and confirmed its correctness, my javascript function seems unable to process it as intended. Here is ...

Why is the oninput function in JavaScript not functioning properly?

After following a practical video tutorial step by step, I tried to implement the code provided (in HTML and JS) but nothing seems to be working! The code snippet from the tutorial includes: var $count = document.getElementById("count"), $textarea = ...

Using Jquery to run a jquery script stored in a variable within jQuery syntax

This question may seem a bit confusing, so allow me to explain further. I am trying to execute a jquery script that is written in a text file obtained through an ajax request. For example, the code I receive from the ajax request looks like this: ($($(" ...

Mandating the inclusion of a directives controller in conjunction with other necessary controllers

Two directives are nested within each other, with one requiring the other using require: '^parentTag' . Both directives have their own controllers. In the parent directive, I can access its controller as the fourth argument in link: function(scop ...

Create a randomized string of numbers that includes specific digits while excluding others

I am struggling with generating strings in JavaScript. Specifically, I have an array of numbers from which a string needs to be generated. The string must contain at least 1 number from the array, but must not contain a specific number given by the user. A ...

What is the best way to implement a CSS Style specifically for a glyphicon icon when it is in keyboard focus?

I have a particular icon representing a checkbox that appears as a glyphicon-star. It is designed to display in yellow when focused on by the keyboard navigation. This feature is intended to help users easily identify their location on a page. However, an ...

Router failing to progress to subsequent page despite alterations in URL

In my react application, I have 3 pages: a login page, a homepage, and a video page. The issue is that when the login button is clicked, it successfully makes a POST request but does not navigate to the next page. Although the URL changes to the required ...

Troubleshooting problems with the CSS code for a progress bar in Gmail

I recently came across a unique progress bar design on Gmail and wanted to implement something similar. I found some code snippets on this webpage: . However, I encountered an issue where the progress bar was only displaying in Internet Explorer but not in ...

Resources that evolve in a dynamic manner within a RESTful API

After browsing through multiple questions with the same title, none of them seem to address my specific concern. I am currently working on a project that I've dubbed as a "RESTful Internet Jukebox". Essentially, it's a RESTful API that can inter ...

Troubleshooting Vue: Why is my component not visible when using v-form and v-text-field components in Vuetify?

Attempting to implement the v-form and v-text-field components from the Vuetify node package. <template> <v-form> <v-text-field label="Test" type="foo"></v-text-field> <v-text-field label="bar&q ...

Decoding JSON information from mutual funds

I'm attempting to extract data from an interactive chart, and I have the JSON file available at this link: http://www.tadawul.com.sa/Charts/MutualFundChartDataDownloader My attempt to import this into Python for data extraction has been met with err ...

Create line items using the quantity code as a reference

I need help implementing a feature that dynamically adds line items based on user input in a quantity text box. For example, if the user enters a quantity of 2, the page should display: Text line for item 1 Text line for item 2 Here is the code snippet ...