I want to post one or more products (depending on what number the user choses) to my api, i have this Product Model:
public class Product
{
[Key]
public int Id { get; set; }
[Required]
[StringLength(50)]
public string DescricaoProduto { get; set; }
[Required]
public float Preco { get; set; }
[Required]
[StringLength(50)]
public string Foto { get; set; }
[Required]
[NotMapped]
public IFormFile FotoFile { get; set; }
public int LayoutNumero1Id { get; set; }
public LayoutNumero1 LayoutNumero1 { get; set; }
}
This class is a foreign key to another class called LayoutNumero1, in which like i said can be one or more Products. I want to know how can i create an endpoint that can take this list of Products using form-data (FromForm type as parameter). For now i have this:
[HttpPost("AddProductsLayoutN1")]
public async Task<IActionResult> AddProductsLayoutN1([FromForm] List<Product> produto)
{
if (ModelState.IsValid)
{
if (produto == null)
{
throw new NullReferenceException("Produto model não existe!");
}
foreach (var p in produto)
{
p.Foto = await SaveImage(p.FotoFile);
_context.Produtos.Add(p);
await _context.SaveChangesAsync();
}
return Ok(new Response
{
Message = "Produto adicionado!",
IsSucess = true
});
}
return BadRequest(new Response
{
Message = "Erro na adição do produto",
IsSucess = false,
});
}
(By the way im trying to add the object LayoutNumero1 in a separate function, in it there are only text fields, and now im trying this one only for adding the Products (the foreign keys), the point is to make two different requests, you think its a good aproach for this kind of problem?)
Thank you so much!!
