Asp.Net Mvc Calling Apis Using Ajax Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    10 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of ASP.NET MVC Calling APIs using AJAX

Explain in Details and Show Important Info: ASP.NET MVC Calling APIs using AJAX

Overview

Why Use AJAX with ASP.NET MVC?

  1. Improved User Experience: AJAX allows for partial page updates, making the application feel more responsive and dynamic.
  2. Reduced Server Load: Only the necessary data is fetched or sent, reducing the amount of data being transferred over the network.
  3. Decoupled Frontend and Backend: AJAX facilitates a cleaner separation between the frontend and backend logic.

Setting Up Your ASP.NET MVC Project

  1. Create an ASP.NET MVC Project:

    • Open Visual Studio.
    • Create a new project and select the ASP.NET MVC template.
  2. Add Required NuGet Packages:

    • Ensure you have jQuery installed, which is typically included by default in MVC projects. jQuery is a popular library for handling AJAX in web applications.

Example Scenario: Fetching Data from an API

Let's consider a simple example where we want to fetch user data from a public API such as the JSONPlaceholder API.

  1. Define the API URL:

    • The endpoint for fetching user data from JSONPlaceholder is https://jsonplaceholder.typicode.com/users.
  2. Controller Setup:

    • In your Controllers folder, add a new controller. Let's name it UserController.cs.
    • Create a view that will make the AJAX call to the API.
  3. View Setup:

    • Create a Razor view, Index.cshtml, under the Views/User folder.
    • Use jQuery to make an AJAX call to the JSONPlaceholder API.

Example Code

UserController.cs

public class UserController : Controller
{
    // GET: User 
    public ActionResult Index()
    {
        return View();
    }
}

Index.cshtml

@{
    ViewBag.Title = "User List";
}

<h2>User List</h2>

<table id="userTable" class="table">
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Phone</th>
        </tr>
    </thead>
    <tbody>
        <!-- Data will be inserted here by AJAX -->
    </tbody>
</table>

@section Scripts
{
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script>
        $(document).ready(function () {
            $.ajax({
                url: 'https://jsonplaceholder.typicode.com/users',
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    var userTable = $('#userTable tbody');
                    $.each(data, function (i, user) {
                        var row = $('<tr></tr>');
                        row.append($('<td></td>').text(user.name));
                        row.append($('<td></td>').text(user.email));
                        row.append($('<td></td>').text(user.phone));
                        userTable.append(row);
                    });
                },
                error: function (xhr, status, error) {
                    // Handle the error here
                    console.log(xhr.responseText);
                }
            });
        });
    </script>
}

Important Information

  1. Handling Success and Error Responses:

    • Success Function: Executes when the AJAX request successfully retrieves data from the API.
    • Error Function: Executes when the AJAX request encounters an error.
  2. Cross-Origin Resource Sharing (CORS):

    • When making AJAX calls to APIs hosted on different domains, ensure that the server supports CORS. JSONPlaceholder APIs are configured to support CORS.
  3. Security Considerations:

    • Be cautious when handling sensitive data via AJAX. Ensure that the server-side code is secure and that any data sent is properly validated and sanitized.
    • Use HTTPS for secure data transmission.
  4. Testing and Debugging:

    • Use browser developer tools to debug and inspect AJAX requests, responses, and network activity.
  5. Performance Optimization:

    • Minimize the amount of data being transferred.
    • Use caching mechanisms where appropriate to reduce the number of API calls.
  6. Error Handling:

    • Implement comprehensive error handling on both the client and server sides to provide meaningful feedback to users in case of failures.

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement ASP.NET MVC Calling APIs using AJAX

Step 1: Create an ASP.NET MVC Project

  1. Open Visual Studio.
  2. Go to File > New > Project.
  3. Select ASP.NET Web Application (.NET Framework).
  4. Enter your project name and click Create.
  5. Choose MVC template and make sure the authentication type is either No Authentication or anything as per your requirement, then click Create.

Step 2: Add an API Controller

We’ll start by adding a simple API controller that returns data in JSON format.

  1. Right-click on Controllers folder in Solution Explorer.
  2. Go to Add > Controller.
  3. Select Web API 2 Controller - Empty and click Add.
  4. Name your controller ProductController and click Add.

Implement the basic Get operation:

using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Web.Mvc;

namespace YourProjectName.Controllers.Api
{
    public class ProductController : ApiController
    {
        // Mock database
        private IEnumerable<Product> products = new List<Product>
        {
            new Product { Id = 1, Name = "Laptop", Price = 899.99 },
            new Product { Id = 2, Name = "Smartphone", Price = 499.99 },
            new Product { Id = 3, Name = "Tablet", Price = 299.99 }
        };

        [HttpGet]
        public IHttpActionResult GetProducts()
        {
            return Ok(products);
        }

        [HttpGet]
        public IHttpActionResult GetProduct(int id)
        {
            var product = products.FirstOrDefault(p => p.Id == id);
            if (product == null)
                return NotFound();

            return Ok(product);
        }
    }
}

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Step 3: Create the View

Next, we will create a view where we will display the list of products from the API using AJAX.

  1. Right-click on the Views/Home folder.
  2. Select Add > View.
  3. Name it Index and click Add.

In the Index.cshtml, add the following code:

@{
    ViewBag.Title = "Products";
}

<h2>Products</h2>

<button id="loadProductsBtn">Load Products</button>

<div id="productsContainer">
    <ul id="productsList"></ul>
</div>

@section scripts {
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#loadProductsBtn').click(function () {
                $.ajax({
                    url: '@Url.Action("GetProducts", "Product", new { httproute = "" })',
                    type: 'GET',
                    dataType: 'json',
                    success: function (data) {
                        var productList = $('#productsList');
                        productList.empty(); // Clear previous list items
                        $.each(data, function (index, product) {
                            productList.append('<li>' + product.Name + ' - $' + product.Price.toFixed(2) + '</li>');
                        });
                    },
                    error: function (xhr, status, error) {
                        alert('Error loading products: ' + error);
                    }
                });
            });
        });
    </script>
}

Step 4: Configure Routes

Ensure you have the proper routes defined for both the MVC and Web API controllers.

  1. Open App_Start/WebApiConfig.cs.
  2. Ensure you have the default route defined:
public static void Register(HttpConfiguration config)
{
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}
  1. Open App_Start/RouteConfig.cs and ensure the MVC route is also defined correctly:
public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        namespaces: new[] { "YourProjectName.Controllers" } // Adjust the namespace
    );
}

Step 5: Run the Application

Run the application by pressing F5 or clicking the Start button in Visual Studio.

  • Navigate to Home/Index in your browser.
  • Click on the "Load Products" button.
  • You should see the list of products dynamically loaded into the #productsList unordered list via AJAX.

Step 6: Explanation of the AJAX Call

Here’s a breakdown of the AJAX call in the Index.cshtml:

$(document).ready(function () {
    $('#loadProductsBtn').click(function () {
        $.ajax({
            url: '@Url.Action("GetProducts", "Product", new { httproute = "" })', // Endpoint of the API
            type: 'GET', // HTTP method
            dataType: 'json', // Expected data type
            success: function (data) { // Success callback
                var productList = $('#productsList');
                productList.empty();
                $.each(data, function (index, product) {
                    productList.append('<li>' + product.Name + ' - $' + product.Price.toFixed(2) + '</li>');
                });
            },
            error: function (xhr, status, error) { // Error callback
                alert('Error loading products: ' + error);
            }
        });
    });
});
  • url: Specifies the endpoint to which the request is sent. We use Url.Action to generate the URL to the GetProducts action in the Product API controller.
  • type: Defines the HTTP method used for the request. In this case, it's a GET request.
  • dataType: The type of data expected back from the server. Here we expect JSON.
  • success: A function to be called if the request succeeds. We populate the #productsList with the retrieved data.
  • error: A function to be called if the request fails. Shows an error alert.

Step 7: Advanced Example - POST Operation

Let's add a feature to add a new product to the list using AJAX with a POST request to the API.

Modify the API Controller:

Add a PostProduct method in the ProductController:

[HttpPost]
public IHttpActionResult PostProduct(Product product)
{
    if (!ModelState.IsValid)
        return BadRequest(ModelState);

    // Add product to mock database and assign ID
    ((List<Product>)products).Add(new Product 
    { 
        Id = products.Max(p => p.Id) + 1,
        Name = product.Name,
        Price = product.Price 
    });

    return CreatedAtRoute("DefaultApi", new { id = product.Id }, product);
}

Add Form to the View:

In the Index.cshtml file, add a form to collect the product details:

<div id="addProductContainer">
    <h3>Add a New Product</h3>
    <form id="addProductForm">
        <label for="productName">Name:</label>
        <input type="text" id="productName" name="Name" required />
        <br />
        <label for="productPrice">Price:</label>
        <input type="number" id="productPrice" name="Price" required step="0.01" />
        <br />
        <button type="submit">Add Product</button>
    </form>
</div>

@section scripts {
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#loadProductsBtn').click(function () {
                $.ajax({
                    url: '/api/Product',
                    type: 'GET',
                    dataType: 'json',
                    success: function (data) {
                        var productList = $('#productsList');
                        productList.empty();
                        $.each(data, function (index, product) {
                            productList.append('<li>' + product.Name + ' - $' + product.Price.toFixed(2) + '</li>');
                        });
                    },
                    error: function (xhr, status, error) {
                        alert('Error loading products: ' + error);
                    }
                });
            });

            $('#addProductForm').submit(function (e) {
                e.preventDefault(); // Prevent form from submitting normally

                var product = {
                    Name: $('#productName').val(),
                    Price: parseFloat($('#productPrice').val())
                };

                $.ajax({
                    url: '/api/Product',
                    type: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(product),
                    success: function (newProduct) {
                        alert('Product added successfully!');
                        $('#productsList').append('<li>' + newProduct.Name + ' - $' + newProduct.Price.toFixed(2) + '</li>');
                        $('#addProductForm')[0].reset(); // Clear form fields
                    },
                    error: function (xhr, status, error) {
                        alert('Error adding product: ' + error);
                    }
                });
            });
        });
    </script>
}

Explanation:

In the form submit handler:

  • e.preventDefault(): Stops the default form submission behavior.
  • product: Creates JavaScript object from the form inputs.
  • $.ajax: Sends the POST request.
    • contentType: Specifies the MIME type of the request body. In this case, it's application/json.
    • data: Converts the product object to JSON string before sending.
    • success: Called if the request is successful. It appends the new product to the list.
    • error: Displays an error message if something goes wrong.

Conclusion

You now have a basic understanding of how to call APIs using AJAX in an ASP.NET MVC application. This example covers both GET and POST HTTP methods and demonstrates dynamic content loading without needing to reload the page.

Top 10 Interview Questions & Answers on ASP.NET MVC Calling APIs using AJAX

Top 10 Questions and Answers on ASP.NET MVC Calling APIs using AJAX

1. What is AJAX in the context of ASP.NET MVC?

2. How do you call an API using AJAX in an ASP.NET MVC application?

Answer: To call an API using AJAX in ASP.NET MVC, first ensure you have the jQuery library included in your project. You can use jQuery's $.ajax() method to send an asynchronous request. Here's a basic example:

<script>
    $(document).ready(function () {
        $('#fetchDataButton').click(function () {
            $.ajax({
                url: '/api/YourApiEndpoint',
                type: 'GET',
                dataType: 'json',
                success: function (data) {
                    // Handle the data returned from the API
                    console.log(data);
                    $('#dataContainer').html(data.Name);
                },
                error: function (error) {
                    console.error('Error fetching data: ' + error);
                }
            });
        });
    });
</script>

In this example, when the fetchDataButton is clicked, the $.ajax() function sends a GET request to /api/YourApiEndpoint, and upon receiving a successful response, it logs the data to the console and updates the HTML content of #dataContainer.

3. Can I use Fetch API instead of jQuery AJAX in ASP.NET MVC?

Answer: Yes, you can use the modern Fetch API to make AJAX calls in an ASP.NET MVC application. Fetch API is a JavaScript API that provides a more powerful and flexible feature set compared to the older XMLHttpRequest. Here's how to use Fetch API to call an API:

document.getElementById('fetchDataButton').addEventListener('click', function () {
    fetch('/api/YourApiEndpoint')
        .then(response => response.json())
        .then(data => {
            // Handle the data returned from the API
            console.log(data);
            document.getElementById('dataContainer').textContent = data.Name;
        })
        .catch(error => {
            console.error('Error fetching data: ' + error);
        });
});

4. How can I handle errors when making API calls using AJAX?

Answer: Handling errors in AJAX calls ensures that your application can gracefully deal with issues like network failures or server-side errors. In jQuery AJAX, you can handle errors using the error callback function. In Fetch API, you can handle errors in the catch block of a Promise.

Example in jQuery AJAX:

$.ajax({
    url: '/api/YourApiEndpoint',
    type: 'GET',
    dataType: 'json',
    success: function (data) {
        // Success handling
    },
    error: function (xhr, status, error) {
        console.log('Error: ' + error);
    }
});

Example in Fetch API:

fetch('/api/YourApiEndpoint')
    .then(response => {
        if (!response.ok) {
            throw new Error('Network response was not ok');
        }
        return response.json();
    })
    .then(data => {
        // Success handling
    })
    .catch(error => {
        console.error('Error: ' + error);
    });

5. How do I handle POST requests when calling APIs using AJAX in ASP.NET MVC?

Answer: When you need to send data to the server, you would typically use a POST request. Here's how to do it using jQuery AJAX and Fetch API:

jQuery AJAX:

$.ajax({
    url: '/api/YourApiEndpoint',
    type: 'POST',
    data: JSON.stringify({ name: 'John Doe', age: 28 }),
    contentType: 'application/json',
    success: function (data) {
        console.log('Success:', data);
    },
    error: function (xhr, status, error) {
        console.log('Error: ', error);
    }
});

Fetch API:

fetch('/api/YourApiEndpoint', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify({ name: 'John Doe', age: 28 }),
})
.then(response => response.json())
.then(data => {
    console.log('Success:', data);
})
.catch((error) => {
    console.error('Error: ', error);
});

6. How can I handle JSON responses from the server when calling APIs using AJAX?

Answer: JSON is the most common format for data interchange between the client and server. To handle JSON responses:

  • In jQuery AJAX, you can set dataType: 'json' which automatically parses the response as JSON.
  • In Fetch API, once you call response.json(), it returns a Promise that resolves with the parsed JSON data.

jQuery AJAX:

$.ajax({
    url: '/api/YourApiEndpoint',
    type: 'GET',
    dataType: 'json',
    success: function (data) {
        console.log(data);
    },
    error: function (xhr, status, error) {
        console.error('Error: ', error);
    }
});

Fetch API:

fetch('/api/YourApiEndpoint')
    .then(response => response.json())
    .then(data => {
        console.log(data);
    })
    .catch((error) => {
        console.error('Error: ', error);
    });

7. How can I send custom headers in AJAX requests?

Answer: You can send custom headers in AJAX requests to include additional information that your server may require, such as authentication tokens.

jQuery AJAX:

$.ajax({
    url: '/api/YourApiEndpoint',
    type: 'GET',
    headers: {
        'Authorization': 'Bearer yourTokenHere'
    },
    success: function (data) {
        console.log(data);
    },
    error: function (xhr, status, error) {
        console.error('Error: ', error);
    }
});

Fetch API:

fetch('/api/YourApiEndpoint', {
    method: 'GET',
    headers: {
        'Authorization': 'Bearer yourTokenHere'
    }
})
.then(response => response.json())
.then(data => {
    console.log(data);
})
.catch((error) => {
    console.error('Error: ', error);
});

8. How can I ensure that my AJAX requests are secure?

Answer: To ensure the security of your AJAX requests, consider the following best practices:

  • HTTPS: Always use HTTPS to encrypt the data transmitted between the client and server.
  • Authentication: Use strong authentication mechanisms such as OAuth2.0 or JWT to secure your APIs.
  • Validation: Validate and sanitize all data received from the client to prevent SQL injection and other security vulnerabilities.
  • CORS: Configure Cross-Origin Resource Sharing (CORS) properly to prevent unauthorized cross-site access.

9. How can I handle cross-origin requests using AJAX in ASP.NET MVC?

Answer: Cross-Origin Resource Sharing (CORS) is a security feature implemented by browsers to prevent web pages from making requests to a different domain than the one that served the web page. In ASP.NET MVC, you can enable CORS using the Microsoft.AspNetCore.Cors package.

In your Startup.cs file:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy", builder =>
            builder.WithOrigins("https://yourdomain.com")
                   .AllowAnyMethod()
                   .AllowAnyHeader());
    });
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseRouting();

    app.UseCors("CorsPolicy");

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });
}

10. What are the benefits of using AJAX in ASP.NET MVC applications?

Answer: Using AJAX in ASP.NET MVC applications provides several benefits:

  • Improved User Experience: AJAX allows parts of a web page to update asynchronously, minimizing page reloads and providing a smoother experience to users.
  • Faster Data Retrieval: Since only necessary data is fetched and updated, AJAX can significantly reduce the time spent waiting for page reloads.
  • Reduced Server Load: By sending and retrieving only the necessary data, AJAX can help reduce the strain on the server.
  • Better Interactivity: AJAX enables developers to create more interactive and dynamic web applications.
  • Enhanced Performance: With less data being transferred between client and server, AJAX can lead to better overall application performance.

You May Like This Related .NET Topic

Login to post a comment.