Home > other >  Unable to append an array of objects to FormData - Vuejs - Asp.net Core
Unable to append an array of objects to FormData - Vuejs - Asp.net Core

Time:07-02

I'm trying to append an array of objects to FormData but I couldn't get this to work for some reason. As it appears, CreateStockIngredientDto doesn't receive values that I pass. I must be missing something. I'm looking for a helping hand here.

Controller Code:

[HttpPost]
[Route("create")]
public int Create(IFormFile invoiceAttachment, [FromForm]CreateStockCommand command)
{
    // do something here.
}

Request Handler

public class CreateStockCommand : IRequest<int>
{
    public DateTime CreatedDate { get; set; }
    public string? SupplierInvoiceId { get; set; }
    public int SupplierId { get; set; }
    public ICollection<CreateStockIngredientDto>? CreateStockIngredientDtos { get; set; 
}

public class CreateStockIngredientDto
{
    public decimal Price { get; set; }
    public decimal Quantity { get; set; }
    public DateTime StockedDate { get; set; }
    public DateTime ExpiryDate { get; set; }
    public int IngredientId { get; set; }
 }

Client Side - Vuejs

const formData = new FormData()

    formData.append('invoiceAttachment', invoiceAttachment.value)
    formData.append('CreatedDate', createdDate.value)
    formData.append('SupplierInvoiceId', supplierInvoiceId.value)
    formData.append('SupplierId', supplierId.value)

    formData.append('CreateStockIngredientDtos', createStockIngredientDtos.value)

    axios.post('stock/create', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
      .then(response => {
        // do something...
      })


  const createStockIngredientDtos = ref([{
  `enter code here`ingredientId: 1, price: 200, quantity: 20, expiryDate: '2022-06-29',
}])

enter image description here

CodePudding user response:

I figured it out finally. I hope it will hope someone else.

    const formData = new FormData()

    formData.append('invoiceAttachment', invoiceAttachment.value)
    formData.append('CreatedDate', createdDate.value)
    formData.append('SupplierInvoiceId', supplierInvoiceId.value)
    formData.append('SupplierId', supplierId.value)

    for (let i = 0; i < createStockIngredientDtos.value.length; i  ) {
      formData.append(`CreateStockIngredientDtos[${i}].ingredientId`, createStockIngredientDtos.value[i].ingredientId)
      formData.append(`CreateStockIngredientDtos[${i}].price`, createStockIngredientDtos.value[i].price)
      formData.append(`CreateStockIngredientDtos[${i}].quantity`, createStockIngredientDtos.value[i].quantity)
      formData.append(`CreateStockIngredientDtos[${i}].expiryDate`, createStockIngredientDtos.value[i].expiryDate)
    }

    axios.post('stock/create', formData, { headers: { 'Content-Type': 'multipart/form-data' } })
      .then(response => {
        if (response.data !== undefined) {
        // do something...
        }
      })
  • Related