Incorporate an additional retrieve functionality in your asp.net web api

I'm brand new to the world of asp.net web api. I have a solid understanding of get(), put(), post() and delete().

For my application, I need to implement two additional get() methods. Here is an overview-

public class StudentController : ApiController 
{
    public IEnumerable Get()
    {
        //returns all students.
    }

    //I want to include this method=======================
    [HttpGet]
    public IEnumerable GetClassSpecificStudents(string classId)
    {
        //retrieve all students from a specific class.
    }

    //Additionally, I would like to add this method=======================
    [HttpGet]
    public IEnumerable GetSectionSpecificStudents(string sectionId)
    {
        //fetch all students from a specific section.
    }

    public Student Get(string id) 
    {
         //retrieves a specific student.
    }
}

In the angularjs controller, there is already a $http.get(..) configured.

My query is, how do I invoke the two extra get() methods from the angular controller.

Answer №1

It's been a while since I worked with asp.net mvc. However, you can try something similar to this:

 public class StudentController : ApiController 
 {
    [Route("students")]
    public IEnumerable Get()
    {
    //returns all students.
    }

    //You may want to include this method=======================
    [HttpGet]
    [Route("students/class/{classId}")]
    public IEnumerable GetClassSpecificStudents(string classId)
    {
        //retrieve all students from a specific class.
    }

    //Another method you might consider adding=======================
    [HttpGet]
    [Route("students/section/{sectionId}")]
    public IEnumerable GetSectionSpecificStudents(string sectionId)
    {
        //retrieve all students from a specific section.
    }
    [Route("students/{id}")]
    public Student Get(string id) 
    {
         //returns specific student.
    }
}

You can also define routes in the routeconfig like this:

routes.MapRoute(
    name: "students",
    url: "students/class/{classId}",
    defaults: new { controller = "Student", action = "GetClassSpecificStudents", id = UrlParameter.Optional }
);

Experiment with it yourself. More information can be found here and here.

Once you have your specified routes, use angular $http.gets for each route.

var url = "whateverdoma.in/students/"
$http.get(url)
   .success()
   .error()

var url = "whateverdoma.in/students/class/" + classId;
$http.get(url)
   .success()
   .error()

var url = "whateverdoma.in/students/filter/" + filterId;
$http.get(url)
   .success()
   .error()

Answer №2

To properly interact with your API, it is recommended to create a custom Angular resource method.

  1. Utilize the angular $resource instead of $http as it follows RESTful principles and common usage patterns.

  2. For more information on how to use $resource, check out this link.

  3. Learn how to include a resource in the $resource service by referencing the example below:

    .factory('Store', function ($resource, hostUrl) {
    var url = hostUrl + '/api/v3/store/';
    
    return $resource("", {  storeId: '@storeId' }, {            
        getSpecific: {
            method: 'GET',
            url: hostUrl + '/api/v3/store-specific/:storeId'
        }
    });
    

    })

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

How can I smoothly navigate to the top of a page using AngularJS?

After receiving an ajax call response using angularjs, I am looking to automatically scroll to the top of the page. The purpose is to bring focus to alert messages displayed at the top of the page upon receiving the ajax response. Appreciate any guidance ...

How to Test React Js API Calls with Jest?

I'm currently in the process of writing test cases for my API call function, but I'm encountering difficulties as I am unable to successfully run my tests. Below is the code for the API call function and the corresponding test cases. export async ...

How can a pop-up be positioned to appear in the right bottom corner using jQuery

Is there a way to position a pop-up at the bottom right corner of the window? I have code that centers the pop-up in the window, but I'm looking to place it specifically at the bottom right corner. $(id).css('top', winH - $(id).height()); ...

List fails to update after new data is inserted

I am currently working on a code snippet that displays a list of employees from mongolab in an unordered list using ng-repeat. The employees are listed correctly; however, when I introduced a button to add new employees, the records are inserted successful ...

How to bypass CORS restrictions in XMLHttpRequest by manipulating HTTP headers?

Currently experimenting with the (deprecated) Twitter API 1.0 For instance, I am interested in retrieving data from the API utilizing AJAX browser requests on cross-origin web pages. This could be a new tab, a local HTML file, or any established website. ...

Displaying minute scale from right to left using jQuery technology

I successfully created a minute scale that is functioning well, but now I am encountering an issue with displaying my scale. Instead of being oriented left to right, I would like it to be displayed from right to left. Can anyone suggest what might be wron ...

remove a specific element from an array

Hey there! I'm attempting to remove only the keys from an array. Here's the initial array: {everyone: "everyone", random: "random", fast response time: "fast response time", less conversations: "less conversatio ...

Is it possible to iterate through an object with multiple parameters in Op.op sequelize?

Currently, I am in the process of setting up a search API that will be able to query for specific parameters such as id, type, originCity, destinationCity, departureDate, reason, accommodation, approvalStatus, and potentially more in the future. const opt ...

Unable to locate the Chart object within the chartjs-plugin-labels.js file

Hello there, I am currently working on an Angular project where I want to incorporate a chart plugin. To achieve this, I executed the following commands: npm install angular2-chartjs npm install chartjs-plugin-labels Following that, I imported it into my ...

Exploring the powerful capabilities of utilizing state variables within styled components

I'm attempting to create a button that changes its state based on the value of a property within an object. Below is the styled component const Btn = styled.button` border-radius: ${props => props.theme.radius}; padding:5px 10px; backgroun ...

AngularJS allows for the creation of a regular expression that specifically matches positive numbers of

Currently, I am working on setting up validations in AngularJS. My goal is to only allow exactly 6 digit positive numbers (whole numbers). However, the regex pattern I am using does not seem to be functioning as expected: "pattern": /^\+?[0-9]+$/ In ...

What is the best way to transfer an array from an Express Server to an AJAX response?

My AJAX request successfully communicates with the server and receives a response that looks like this: [{name: 'example1'}, {name: 'example2'}] The issue arises when the response is passed to the client-side JavaScript code - it is t ...

When the user presses either the refresh button or the back button, they will be redirected

After the user presses refresh or uses the browser back button, I need to redirect them to a specific page in order to restart the application. My JavaScript code is as follows: var workIsDone = false; window.onbeforeunload = confirmBrowseAway; function ...

Exploring Deeply Nested Routing in Angular

I've been exploring the use of multiple router outlets and encountered an issue. When using the navigateBy function of the router, I am unable to view my child route and encounter an error. However, when I access it via the routerLink in HTML, I get ...

Struggling to incorporate infinite scroll feature into JSON script that is already functioning smoothly

After developing a phonegap application, I created a page called photos.html to fetch photos from my server using JSON. However, despite successfully retrieving all the photos stored in my MySQL database on the server with JSON, I struggled to integrate In ...

attempting to merge two arrays into a single union

I am looking for a way to create a new array that contains only unique values from both the first and second arrays, maintaining their original order. This is my current approach: function union(first, second) { return first.filter(function(value) { ret ...

Pressing the submit button within a form in Ionic2 triggers the Ion-Input onSubmit event

In my form, there is an ion-button and an ion-input included. The ion-button is not meant for submitting the form. When I try to edit a value in the input field and press "ok", I expect the keyboard to hide. However, the ion-button reacts to this event an ...

What could be causing the issue of receiving the error message: "Uncaught TypeError: Cannot read property 'Title' of undefined"?

I am currently working on developing an AJAX web application. One of the functions I have is aimed at requesting a JSON object and then utilizing it to refresh the website content. Below is the portion of JavaScript causing an issue (Lines 8 - 16): windo ...

Is data shared globally for each HTTP/Session request?

QUERY: Is there a method to establish a variable storage specific to each session or HTTP request? The variable should be accessible globally within that session/request/connection, without the need to pass it between functions. For instance (as an examp ...

What is the best way to display both an employee's name and ID on a single line using CSS and HTML?

I am currently working on an asp.net MVC app and facing an issue with adding employee ID and employee name on the same line, similar to the web design provided. I need to make modifications using HTML and CSS to achieve this. The problem is that I am unab ...