Pass an array of data from an AngularJS application to a WebAPI endpoint, then retrieve and process that

Imagine having an array within the client-side model:

        vm.dataSheets = [
        { value: 0, text: localize.getLocalizedString('_ProductsAndServices_'), selected: selected},
        { value: 1, text: localize.getLocalizedString('_Holidays_'), selected: selected },
        { value: 2, text: localize.getLocalizedString('_Locations_'), selected: selected },
        { value: 3, text: localize.getLocalizedString('_OpHours_'), selected: selected },
        { value: 4, text: localize.getLocalizedString('_Users_'), selected: selected }
    ];

This array is connected to a checkbox list in the HTML. The goal is to send the values of the checked items to the web API. By using angularJS, you can filter the selected objects like this:

$filter('filter')(vm.dataSheets, { selected: true })

Instead of getting the entire object array, is there a quicker way to just retrieve the selected values as 1, 2, 3, etc...?

Currently, the data is sent to the Web API as shown below:

  var fd = new FormData();
        fd.append('file', file);
        fd.append('clientId', $rootScope.appData.clientId);
        fd.append('sheets', $filter('filter')(vm.dataSheets, { selected: true }));

        $http.post("TIUSP/systemengine/ClientSupply", fd, {
            withCredentials: true,
            headers: {'Content-Type': undefined },
            transformRequest: angular.identity
        }).success(function () {

        }

How can the selected values be retrieved in the web API? When using

HttpContext.Current.Request["sheets"];

a string such as [object, object][object, object] is returned.

Answer №1

If you want to retrieve the chosen values as an array with IDs, you can implement a customized filter:

app.filter('selected', function() {
  return function(items) {
    var filtered = [];
    for (var i = 0; i < items.length; i++) {
      var item = items[i];
      if (item.selected === true) {
        filtered.push(item.id);
      }
    }
    return filtered;
  };
});

Then, apply it like this:

var fd = {
    'file': file,
    'clientId': $rootScope.appData.clientId,
    'sheets': $filter('selected')(foo.results)
};

    $http.post("TIUSP/systemengine/ClientSupply", fd, {
       withCredentials: true,
       headers: {'Content-Type': undefined },
       transformRequest: angular.identity
    }).success(function () {    
}

This will generate a result similar to this:

{
   file: 'path-to-my-filez/image.png',
   clientId: 11,
   sheets: [1,2,3,4]
}

In your Web API Controller

Construct a class that corresponds to the parameters being transmitted in your request:

public class ClientSupplyViewModel
{
    public string file {get; set;}
    public int clientId [get; set;}
    public int[] sheets {get; set;}
}

Next, utilize it within your controller:

[HttpPost]
public HttpResponseMessage ClientSupply(ClientSupplyViewModel data)
{

}

The controller mentioned above is just a sample. The crucial aspect is the data parameter containing your File, ClientId, and the integer array.

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 data returned by axios is not equivalent to the parsed JSON response from the request

When making an axios request, I use the following code: const response = await axios({ url, method, headers: headersObject, data, params: params || {}, }); After making the request, I examine the response: console.log('response.request.resp ...

What is the method for adding 24 hours to a 12-hour timestamp while preserving the AM and PM designation?

I have created the following code to display real-time, but I am struggling with adding a timestamp that switches from 24-hour format to 12-hour format with AM and PM. setInterval(function() { var date = new Date(); var hours = date.getHours(); va ...

Calculating the minimum, maximum, and average values from the set of five entered numbers

My goal is to develop a program in C that collects 5 input numbers and then stores them in an array. The challenge is to calculate the min, max, and average of the MINIMUM AND MAXIMUM numbers entered, not all five. I've encountered an issue with my co ...

What could be causing my AJAX code to fail in retrieving information from an API?

Hey everyone, I'm new here and hoping to get some help with an issue I'm facing. I've written a code to fetch data from an API and display it on my HTML page, but for some reason the AJAX code isn't working. There's nothing showing ...

Benefits of Using Slice Over Arrays in GO

Currently in the process of learning GO. The documentation states that slices are more versatile than arrays. Despite this, I am struggling to understand when slices would be most beneficial to use. Can anyone provide a hypothetical scenario where using ...

Issue with Material UI React JS Select component: Unable to deselect multiple values when more than one item is selected

Implementing a multiselect dropdown in material ui with specific conditions: The dropdown will contain [0 Apples, 1 Oranges, 2 Grapes]. By default, 0 Apples should be selected. None of the options can be unselected. If 0 Apples is selected and the user se ...

Need to include files within an electron / express application

I'm encountering challenges while setting up an app with: electron express (using mustache templating) firebase My struggle lies in correctly requiring files. The issue seems to stem from the varying "scope" being the electron app or express app, re ...

Sequelize querying using the `WHERE NOT EXISTS()` condition

I am currently working with a many-to-many relationship setup in my database: var Genres = db.define('Movie', { name: { type: Sequelize.STRING(100), allowNull: false }, description: { type:Sequelize.STRING(), ...

The custom modal does not seem to be compatible with the CSS3 animation library,

I managed to create my own Full page modal successfully, but now I want to enhance it with an animation. I am attempting to use animate.css to add animation effects such as zoomIn or zoomOut, but it's not working as expected. Here is the link to my J ...

Encountering a ReferenceError while attempting to implement logic on a newly created page

I've been experimenting with building a website using the Fresh framework. My goal was to add a simple drop-down feature for a button within a navigation bar, but I'm struggling to figure out where to place the necessary code. I attempted creatin ...

Converting ByteBuffer to String in iReport: A How-To Guide

I am facing an issue with using the Cassandra plugin in iReport. Even though the plugin is properly embedded in iReport, I am only able to fetch 3 columns through the CQL written script. The column names appear in Read Fields as well. However, the problem ...

The display of data attributes is not being rendered correctly

Check out the fiddle I'm currently working on: http://jsfiddle.net/7Z8wY/9/ The HTML section looks like this: <div class="container"> <div class="right"> <div id="cityList" class="inner-table"></div> </div> ...

Leveraging jQuery to establish headers in an ajax request

I want to integrate an Office 365 Rest API into my application. When I test the URL within the same browser session, I can view some XML data. https://i.sstatic.net/1lbZZ.png However, when I try pasting the URL into an incognito window, I encounter this ...

Is it possible to translate the IIFE functions of threejs into ES6 format?

I'm currently facing a challenge in breaking down my threejs project into smaller modules. One specific function that I'm struggling with is the following: var updateCamera = (function() { var euler = new THREE.Euler( 0, 0, 0, 'YXZ&apos ...

What is the difference between using "src" in a script tag to reference a resource on the local filesystem versus a non-local filesystem?

Assuming I have an HTML page that includes a script tag like the following: <SCRIPT SRC="./xxx.js"></SCRIPT> In what scenarios would the ./xxx.js file be accessed from the local filesystem? I comprehend that the URI/URL ./xxx.js points to "t ...

Encountering a 401 error message with a 'truncated server' response while using Google Apps Script

I'm currently working on a code snippet that looks like this. function method3() { var spreadsheetID = '1BGi80ZBoChrMXGOyCbu2pn0ptIL6uve2ib62gV-db_o'; var sheetName = 'Form Responses 1'; var queryColumnLetterStart = ...

Determine the closest parent using jQuery

When using jQuery, the closest function can be called to locate the nearest parent element. For instance, if there is an a within a li within a ul within a td within a table, determining whether the ul parent is closer than the table parent may not always ...

How to eliminate query strings from the current page's URL using JavaScript

Looking for a way to remove the querystring from the current page URL using JavaScript when a button is clicked. Can someone please provide the necessary code for this? ...

Learn the process of showcasing database content on a webpage with an interactive feature that enables users to choose and access additional details

Apologies if this question has been asked before, I have searched for a solution but my web development knowledge is limited. To better understand my issue, you can visit the site at 000freewebhost by following this link: In summary, I am trying to select ...

Is it acceptable to manipulate the prevState parameter of the setState function as mutable?

It is commonly known that directly modifying this.state is not recommended, and instead setState should be used. Following this logic, I assumed that prevState should also be treated as immutable, and setState should always involve creating a new object i ...