Posting an array as form data in Angular Typescript: A step-by-step guide

Hello there, I'm currently developing an application using Angular 8 and integrating web.api within .net core 2.2.

One of the challenges I encountered is dealing with multi-selectable checkboxes in a form that also includes "regular" inputs and file upload functionality.

To handle the array of numbers from the multi-selectable checkboxes, I convert my FormGroup into FormData before posting it to the server. I manually add the file and the array of integers like this:

data.append('locationsSecondaryIds',
    new Blob( [ JSON.stringify(this.profilePersonalData.locationsSecondaryIds)], { type : 'application/json' } ) );
    if (this.file) {
        data.append('document', this.file, this.file.name);
    }

The variable locationsSecondaryIds represents a number array.

I have attempted to send the data without converting it to a Blob by simply sending [1,1], but unfortunately, the server is unable to convert it to a List on receiving the request.

If anyone has any suggestions or solutions to this issue, I would greatly appreciate your help!

Thank you in advance for your assistance :-)

Answer №1

I encountered a similar situation and approached it like this.

This is how I structured my Angular component.ts File:

const formData = new FormData();
formData.append('Parameter1', "Some String Value");
formData.append('Parameter2', this.currentUserId.toString());
for (const index in this.arrayValues) 
{
    // Instead of converting this.arrayValues to string, I looped through each item and added it to the form.
    formData.append(`ArrayValue[${index}]`,this.arrayValues[index].toString());
}
for (const file of this.importedFiles)
{
    formData.append('Files', file);
}

After that, I sent it to an asp.net core web API where everything functioned smoothly.

In my server side C# Class:

public class SomeClass
{
    public string Parameter1 { get; set; }
    public int Parameter2 { get; set; }
    public string[] ArrayValue { get; set; }
    public IFormFile[] Files { get; set; }
}

Note: Remember to use [FromForm] attribute on your parameter in the action method.

In the Asp.Net Core Web API Controller action method:

public async Task<IActionResult> SomeMethod([FromForm] SomeClass someClass)
{
    ...
}

Answer №2

If you want to select multiple checkbox values and add them to a form data, you can follow these steps before clicking the submit button:

const selectedValues = [];
selectedValues = this.skillForm.value.subjects; // 'subjects' here refers to a multi-select dropdown
let selectedString = selectedValues.toString(); // You can convert the values to integers based on your database column type
let formData = new FormData();
formData.append('selectedValues', selectedString);

Answer №3

Following fingers10's advice was the key to solving my issue. I modified my code by incorporating an array of objects, using their recommended approach as shown below.

    for (const index in voteData.feedMessageTags) {
        // Instead of converting this.arrayValues to a string, I loop through each item and add it to the form.
        formData.append(`feedMessageTags[${index}].key`, voteData.feedMessageTags[index].key);
        formData.append(`feedMessageTags[${index}].value`, voteData.feedMessageTags[index].value);
    }

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

Loop through an array of elements in JavaScript and retrieve the element with the largest pixel size

I am facing a challenge with elements positioned absolutely on a web page. My goal is to iterate over these elements and identify the one with the highest top value. I attempted two different approaches: const elems = document.querySelectorAll('.ind ...

using angular and firestore to grant public reading permission for a document

As a student developer, I recently integrated Firestore into my Angular app and encountered some challenges with the security rules. My goal: I want to display a Firestore document in an Angular view using template binding. The document should be visible ...

Pressing Enter in a Material-UI Dialog does not trigger form submission

I am currently facing an issue with my modal dialog component. I have two buttons within the dialog, with one functioning as a submit button. My goal is to make the 'Enter' key trigger the submit action as well. Below is the code snippet for thi ...

Troubleshooting issue: Unable to Subscribe to Subject in Angular 5+ with RxJS

My service has an observable that is subscribed to, and the payload is passed to a subject in the service. However, when I subscribe to the subject in my component, nothing happens. I expect to see the output from console.log in the .subscribe method withi ...

What is the best way to transfer the userId from the browser to protractor?

Using *ngFor in my angular2 component to render users has been successful. <ul> <li *ng-for="let user of users"> <input [(ng-model)]="user.name"> <button (click)="remove(user._id)">Remove</button> ...

Changing the background color of .pane and .view elements in an Ionic web application using JavaScript

Looking to modify the background-color of two css selectors, .pane and .view, that are located within the ionic.css file. Despite multiple attempts to do so using JavaScript directly in the index.html file, the changes are not reflected. The code snippet ...

Using the Post method in Angular will result in a 400 status code being returned

I am a student developer working with the Angular platform. I have my own API and a post method that looks like this: [HttpPost] [Route("login")] public async Task<ActionResult<User>> LoginUser([FromBody] User _user) { var joinedUser = _co ...

Experimenting with key directive in the newest version of Angular (9)

I'm currently testing a directive, but I am facing an issue where the length of the value in the directive is always undefined. What could be causing this problem? @Directive({ selector: '[evAutoTab]' }) export class EvAutoTabDirective { ...

Using Ionic to send email verification via Firebase

I have encountered an issue while attempting to send an email verification to users upon signing up. Even though the user is successfully added to Firebase, the email verification is not being sent out. Upon checking the console for errors, I found the f ...

Challenges when transitioning from Angular 8 to Angular 9

After transitioning from Angular 8 to Angular 9, I encountered the following issues. Despite removing and reinstalling node_modules multiple times, the problems persist: An unhandled exception occurred: Cannot find module 'webpack/lib/ParserHelpers&ap ...

Limit the typescript generic type to only a singular string literal value, preventing the use of unions

Within my project, I have introduced a generic entity type that utilizes a generic to determine a field type based on a specific set of string literals: type EntityTypes = 'foo' | 'bar' | 'baz'; type EntityMappings = { foo: ...

I am having trouble viewing the input value on my Angular5 form

Here is the HTML code snippet that I've written: <input type="text" name="fechainscripcion" #fechainscripcion="ngModel" [(ngModel)]="alumno.fechainscripcion" value="{{today | date:'dd/MM/yyyy'}}" class="form-control" /> This is a seg ...

How can we effectively map Typescript Enums using their keys without relying on a Map?

Consider the following Enum instances: export enum TopicCategories { GUIDES = 'Guides', TASKS = 'Tasks', CONCEPTS = 'Concepts', FORMULAS = 'Formulas', BLOGS = 'Blogs' } export enum Top ...

Fill in the missing keys, values, and data within the JSON object

My JSON data consists of various objects with unique dates and site names. The dataset contains distinct dates such as: 2019-10-01, 2019-10-02, 2019-10-03, 2019-10-04, 2019-10-05. Some dates might be missing for certain sites in the dataset. For example, o ...

Upon launching Google Chrome, a series of errors plague the WSL2 Ubuntu setup while running Karma and Jasmine for Angular testing

My Angular project utilizes Google Chrome for testing with Karma & Jasmine, but upon starting Chrome, I encounter multiple errors. Despite trying various solutions found on Stack Overflow, none have been successful. The versions in use are: Chrome 99.0.4 ...

Convert potentially undefined boolean into a boolean by utilizing "!!"

Just had a thought - when dealing with a potentially undefined boolean variable, is it advisable to cast it as a boolean using the double exclamation mark? Consider this interface: interface Example { id: number; isDisabled?: boolean; } We then have ...

Begin the NextJS project by redirecting the user to the Auth0 page without delay

I am new to coding and currently working on a project using Typescript/NextJS with Auth0 integration. The current setup navigates users to a page with a login button that redirects them to the Auth0 authentication page. However, this extra step is unneces ...

Can a File Object be transmitted to an AWS Lambda function via API Gateway using JavaScript?

Can a JavaScript File Object be passed from a browser to AWS Lambda via API Gateway (ultimately to S3)? I am working with TypeScript and React. Environment Frontend TypeScript React AWS Amplify (for API module) Backend(AWS Lambda) Node.js Expecta ...

When passing parameters through a URL in TypeScript, the display shows up as "[object object]" rather than as a string

Hey there! I'm trying to pass some string parameters to my URL to fetch information from an API. Everything seems fine, and when displayed in an alert, the URL looks exactly as it should (no [object, object] issue). var startDate = "2020-09-20"; var ...

Implement a T3 App Redirect in a TRPC middleware for unsigned users

Is there a way to implement a server-side redirect if a user who is signed in has not finished filling out their profile page? const enforceUserIsAuthed = t.middleware(({ ctx, next }) => { if (!ctx.session || !ctx.session.user) { throw new TRPCE ...