What is the best way to pass a data array from angular to web API C#
Loading
What is the best way to pass a data array from angular to web API C#
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Sangeetha SRank #212 · 11.4K reputationPosted Nov 15, 2024, 1:51 AM EST
Passing a data array from an Angular application to a C#
Angular code
import { HttpClient } from '@angular\/common\/http';
import { Injectable } from '@angular\/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private apiUrl = 'https:\/\/yourapiurl.com\/api\/data';
constructor(private http: HttpClient) {}
sendData(dataArray: any[]) {
return this.http.post(this.apiUrl, dataArray);
}
}
Component
import { Component } from '@angular\/core';
import { DataService } from '.
@Component({
selector: 'app-your-component',
templateUrl: '.\/your-component.component.html',
})
export class YourComponent {
constructor(private dataService: DataService) {}
submitData() {
const myDataArray = [1, 2, 3, 4];
this.dataService.sendData(myDataArray).subscribe(response => {
console.log('Data sent successfully', response);
}, error => {
console.error('Error sending data', error);
});
}
}
Web api
[ApiController]
[Route("api/[controller]")]
public class DataController : ControllerBase
{
[HttpPost]
public IActionResult ReceiveData([FromBody] int[] dataArray)
{
return Ok(new { message = "Data received successfully", receivedData = dataArray });
}
}
Jayraj ChhayaRank #304 · 8.2K reputationPosted Nov 15, 2024, 1:52 AM EST
To pass a data array from Angular to a C# Web API, you can utilize the
HttpClientservice in Angular to send a POST request containing the array. The C# Web API can then receive this data as a parameter in the action method.Angular Code
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class DataService { private apiUrl = 'https://yourapiurl.com/api/data'; constructor(private http: HttpClient) {} sendData(dataArray: any[]) { return this.http.post(this.apiUrl, dataArray); } }C# Web API Code
[HttpPost] [Route("api/data")] public IActionResult ReceiveData([FromBody] List dataArray) { if (dataArray == null || !dataArray.Any()) { return BadRequest("No data received."); } // Process the data array return Ok("Data received successfully."); }The Angular service sends a data array to the specified API endpoint, and the C# Web API method processes the incoming data. Ensure that the API is configured to accept JSON data, which is the default behavior when using
[FromBody].