"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

Is there an issue connecting .NET to MySQL using ODBC 5.3?

I am encountering an issue with my ASP.NET webform .NET 4.5 website that utilizes MySQL ODBC to communicate with the MySQL Database. Everything works fine with the 32-bit driver version 5.1.13, but when I upgrade to version 5.3.4, I receive the following e ...

How can I add a JavaScript-created element into a Primeng TurboTable component?

I am in the process of replacing a custom-made table with PrimeNG's turbotable. The issue I'm facing is that when I try to insert buttons into the table that call specific JavaScript functions, they end up displaying as [object HTMLInputElement] ...

Tips for preserving viewstate in jqxGrid in asp.net?

Currently, I am utilizing the jqxGrid component within the jqWidgets library. However, I encountered an issue where after performing an event on the page that triggers a postback to the server, the grid appears empty. This behavior makes sense since the ...

When attempting to compile Angular in production mode, errors may arise such as the Uncaught SyntaxError caused by an Unexpected token '<'

I encountered some errors in the console of my Angular 8 app. When I opened the browser window, it was blank and this error appeared: Uncaught SyntaxError: Unexpected token '<' I tried running different ng build commands such as: ng build --b ...

Utilizing the default event object in ag-Grid's event methods with JavaScript

I am a newcomer to ag-grid and I need help with calling event.preventDefault() in the "cellEditingStopped" grid event. Unfortunately, I am struggling to pass the default JavaScript event object into it. Is there a way to make this work? Additionally, I al ...

Upgrading from Angular 5.2 to 6.0: Facing an issue where angular.json does not replace angular-cli.json

After diligently following the official documentation to upgrade from Angular 5.2 to Angular 6.0 (with the end goal of migrating to Angular 13), I found myself at a standstill. Executing the command NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@6 update @an ...

Accessing results from geocoder.geocode is restricted to local variables only

I need to extract longitude and latitude coordinates from google.maps.GeocodeResults in order to store them in an external Array<any>. Currently, I am able to display results[0], but encounter an OVER_QUERY_LIMIT error when attempting to add it to t ...

Navigating the parent scope in Angular using TypeScript

Is there a way to access the parent Controller's scope from within the TypeScript class? Here is the code snippet: export class EntityOverviewCtrl extends AbstractCtrl { public static $inject = ["$state", "$http", "CurrentSession"]; publi ...

Retrieving Values from Components in Angular 6

Encountering an issue while retrieving values from different components. The scenario involves 2 components - ReceiveBookingManageComponent as the first component and DriverTablePickerComponent as the second one. The problem arises in DriverTablePickerCo ...

Using templateUrl from a remote server in Angular 2 can be achieved by specifying the complete URL

My file contains the following component with a remote URL: @Component({ templateUrl: '/mobilesiteapp/template/?path=pages/tabs' }) export class TabsPage { } Unfortunately, when compiling, I encountered this error message: [13:28:50] Error ...

Obtain the true HOST address while the ASP.NET server is positioned behind an ISA server acting as a reverse proxy

Can anyone advise on retrieving the original HOST IP when a web server is located behind an ISA server functioning as a reverse proxy? Unlike other reverse proxies such as squid, the ISA server does not include the "X_FORWARDED_FOR" value in the request h ...

Implementing a NONCE store using a straightforward cache system in ASP.net

How can we effectively handle NONCE requirements (similar to digest authentication) within the ASP.net pipeline? One approach could be utilizing a singleton with a straightforward dictionary-based object that stores used NONCE values and includes a timer ...

Handling errors in a customized way within a web method that returns an XML document

I have a client who has a web method setup like this: [WebMethod] public XmlDocument Send(string stuff) { // ... } There are certain exceptions that occur and the code currently re-throws them, triggering ASP.Net's default exception handling. W ...

Tips for concealing a dynamic table element in Angular 9

I have dynamically generated columns and rows in a table. Here is my HTML for the table component: <table id="tabella" class="table table-striped table-hover"> <thead class="thead-dark"> <tr> <th *ngFor="let header of _ob ...

Exploring the capabilities of automation testing with charts.js and the latest version of Angular

While working on my testing automation for charts.js, I utilized the ngContext object to retrieve data with this code snippet: document.getElementsByTagName('chart-dataset')[0].__ngContext__. However, since upgrading to angular 14, it seems that ...

Angular2 Collaborative Module

Hey, I've been wondering about something. So, I have a bunch of components that I want to use in various parts of my application. However, rather than loading all these components right from the start, I'd prefer to load them on demand (lazy load ...

URL base not refreshing on globalized Angular web application

I have recently expanded my Angular web app to include new languages, but I am encountering a strange issue. Despite setting up all the new languages in my angular.json file and linking their respective language files correctly, I am facing a problem with ...

The Scrollable feature in Material2 cdk remains unutilized due to

Trying to implement the new APIs for listening to scroll events in Material2 has proven challenging. I followed the steps of importing the ScrollDispatchModule in my app.module.ts file and marking a container with the cdkScrollable directive: <div cdkS ...

Unlocking the Power of Passing Props to {children} in React Components

Looking to create a reusable input element in React. React version: "react": "17.0.2" Need to pass htmlFor in the label and use it in the children's id property. Attempting to pass props to {children} in react. Previously attempte ...

How can the NavBar be refreshed once a user logs in?

I recently followed a helpful guide on implementing a login system in my React TS application. However, I encountered an issue with the NavBar component within my app compared to how it was coded in the App.tsx file of the guide. Specifically, I found it c ...