"Is it possible to add an entire object to formData in one

I am looking to send both an image list and product data to an ASP.net api using formData. I have successfully sent the images, but now I am struggling with appending the entire object. I have come across some methods in JS like JSON.stringfy(object) or

Object.keys(object).forEach(key => formData.append(key, object[key])); 
, but none of them seem to work for me.

angular http service

 updateProduct(imageProductVM:ProductImageViewmodel): Observable<any> {
    const formData = new FormData()
    // imageProductVM.product ??

    for (const photo of imageProductVM.files) {
      console.log(photo)
      formData.append('files', photo)
    }
    return this.http.post(this.apiURL + '/product/', formData, {headers:{"ContentType": "multipart/form-data"}})
  }

asp.net api

[HttpPost]
public async Task<ActionResult> AddProduct([FromForm] ProductService ser)    
{            
   return Ok();
}
public class ProductService
{
   public Product? product { get; set; }

   public List<IFormFile>? files { get; set; }
}

Answer №1

It slipped my mind to mention that my product object contains nested objects. Huge thanks to W.S for providing the valuable information.

I found this answer very useful in guiding me on how an object should be structured for ASP.net applications. Here is the format it should take in my scenario:

product.id *value*
product.supplierId *value*
product.supplierName *value*
product.title *value*
product.description *value*
product.vendor *value*
product.vendorId *value*
product.documents[0].id *value*
product.documents[0].url 
product.documents[0].keywords 
product.attributes[0].attributeId *value*
product.attributes[0].attributeName *value*
product.attributes[0].type A
product.attributes[0].value 2

Following this, I utilized the code below to transform my object into a compatible view:

productEntriesIteration(object:object, j:number, nestedKey:string) {
    Object.entries(object).forEach(([key, value], i)=> {
      if (value) {
        if (typeof value == "string") {
          this.appendSingleField(key, nestedKey,j,value);
        }
        else if (typeof value == "number") {
          if ( Number(value) === Number(value) && Number(value) !== (Number(value) | 0)) {
            value = value.toString().replace(".", ',')
          }
          this.appendSingleField(key,nestedKey,j,value)
        }
        else if (typeof value.getMonth === 'function') {
          this.appendSingleField(key, nestedKey, j, value.toISOString())
        }
        else if (Array.isArray(value)) {
          for (let val in value) {
            if (typeof value[val] == "object") {
              this.productEntriesIteration(value[val],  Number(val), key)
            }
            else if (typeof value[val] == "number"){
              this.appendSingleField(key, nestedKey, j, value[val])
            }
               else {
              this.appendSingleField(key, nestedKey, j, value[val])
            }
          }
        } else if (typeof value == "object") {
          this.productEntriesIteration(value, -1, key)
        }
      }
    })
    return this.formData
  }


  appendSingleField(key:string, nestedKey:string, i:number, value:any) {
    if (i == null) {
      this.formData.append('product.'+key+'',value)
    } else if (i == -1) {
      this.formData.append('product.'+nestedKey+'.'+key,value)
    } else {
      this.formData.append('product.'+nestedKey+'['+i+'].'+key,value)
    }
  }

I trust this explanation will benefit others in similar situations

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

Although VSCode is functioning properly, there seems to be a discrepancy between the VSCode and the TS compiler, resulting in an

While developing my project in VSCode, I encountered an issue with accessing req.user.name from the Request object for my Node.js Express application. VSCode was indicating that 'name' does not exist in the 'user' object. To address thi ...

Encountering an issue when running the command "ng new my-app" after updating the @angular/cli package

npm version 7.5.4 has been detected, but the Angular CLI currently requires npm version 6 to function properly due to ongoing issues. To proceed, please install a compatible version by running this command: npm install --global npm@6. For more information ...

Connect the backend with the frontend using React.js

I am currently faced with the task of developing the front end for an existing backend project. The original front end was built using Angular, but I am opting to recreate it using React. However, I am unsure about how to establish a connection between t ...

Unable to invoke server-side function via Ajax

I have implemented 3-tier architecture in my demo application. Currently, I am facing an issue while trying to invoke a method from the business logic layer using Ajax in the presentation layer. It seems like there is an error related to passing the URL. ...

Angular consistently marks form controls as mandatory, even in the absence of validators

Recently, I have been working on this code snippet where I make use of a deepCopy function to ensure that I avoid any unexpected pass by reference issues. const formGroup = this.allowances() formGroup.removeControl('allowanceEndDate') con ...

Angular 2 decorators grant access to private class members

Take a look at this piece of code: export class Character { constructor(private id: number, private name: string) {} } @Component({ selector: 'my-app', template: '<h1>{{title}}</h1><h2>{{character.name}} detai ...

Is there a way to deactivate the spin buttons for an input number field?

Is there a way to create an input element with type number in Vue using createElement() in TypeScript and then disable the spin buttons for increment and decrement? I attempted to use the following CSS: input[type=number]::-webkit-inner-spin-button, input ...

Angular 17 SSR Swiper 11: Why aren't the breakpoints functioning as expected?

I'm currently struggling with implementing breakpoints in the swiper code. Despite multiple efforts, I have not been able to successfully integrate the breakpoints, and it seems like the functionality is not working as intended. I'm reaching out ...

Angular's Mysterious Pipe

When navigating to the indice page, I want to adjust the number formatting in the cours column to display two decimal places. For instance: 11345.654589 should be displayed as 11345.65. https://i.stack.imgur.com/tjvWb.png To achieve this, I have created ...

Looking to reallocate information, paginate, and sort each time a new row is added to the mat-table

In my application, I have a customized <mat-table> with an implemented addRow() function that adds a new row to the table using default values based on the data type. The challenge I'm facing is that each time a new row is added, I find myself ...

The error message "Error: cannot read property ‘setDirtyAttribute’ of null" may be encountered when attempting to use the method YourModel.create({...}) in ember-typescript-cli

Encountering the error cannot read property 'setDirtyAttribute' of null even when using YourModel.create({...}) in ember-typescript-cli to instantiate an EmberObject. Model: import DS from 'ember-data'; import {computed} from "@ember/ ...

What is the best way to utilize a component's property within a parent abstract class?

Custom Class: export abstract class CustomClass { constructor(); customMethod() { // accessing the name input of SomeComponent here; } } Some Component: export class AnotherComponent extends CustomClass { @Input() name: string; constru ...

Differences between useFormState and useForm in Next.js version 14

Currently, I am intrigued by the comparison between using the react hook useForm and the react-dom useFormState. The Nextjs documentation suggests utilizing useFormState, but in practice, many developers opt for the react hook useForm. I am grappling with ...

Unable to access specific data from the JSON string retrieved from the backend, as it is returning a value of undefined

After receiving a JSON string from the backend, my frontend is encountering issues when trying to index it post using JSON.parse(). The indexed value keeps returning as undefined, even though it's a JSON object literal and not within an array. For th ...

LeafletJS tiles are only loaded once the map is being actively moved

Currently, I am facing an issue while trying to load a simple leaflet map in my Ionic 2 application. The problem is that not all tiles are loading correctly until the map is moved. this.map = new L.Map('mainmap', { zoomControl: false, ...

Creating dynamic captions in an Angular grid is an essential feature for enhancing the

Is there a way in Angular to dynamically update the grid titles based on an array of elements in the model? How can I display them as captions? For instance, imagine we are currently in week 202010. I would like to automatically generate the next five wee ...

"Facing an issue where ts-node is not recognizing d.ts files, despite tsc being able to compile them

I am currently using typescript along with express and attempting to enhance the request object in express. Below is my server.ts file: import express, { Request, Response } from "express"; const app = express(); app.use(function(req: Request, res: Respo ...

Implementing TypeScript for augmented styling properties in a component - a guide

I have custom components defined as follows: import React from 'react'; import styled from '../../styled-components'; const StyledInput = styled.input` display: block; padding: 5px 10px; width: 50%; border: none; b ...

Is there a way to initiate a JSON POST request from an iOS gadget and direct it towards an ASP.NET URL?

I am currently developing an application that requires data sharing with a windows server. After researching various examples online, I have come up with the following implementation below. Although both the iOS code and web-service are functioning properl ...

The specified type 'IterableIterator<number>' does not belong to either an array type or a string type

Encountering an error while attempting to generate a dynamic range of numbers. Error: Type 'IterableIterator<number>' is not recognized as an array or string type. Use the compiler option '--downlevelIteration' to enable iteratio ...