2

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!!

1 Answer 1

1

I found the solution that i needed. I ended up creating a single endpoint for reciving LayoutNumbero1 data and the Products data (the foreign keys). I just passed LayoutNumero1 as parameter like this:

 public async Task<IActionResult> AddLayoutNumero1([FromForm] LayoutNumero1 produto)
    {
        //some stuff here for saving in db
    }

And on client i created this form data content and posted it to the endpoint:

var formContent = new MultipartFormDataContent();

            var numeroDoProduto = 1;
            var i = 0;

            LayoutNumero1 layout = new LayoutNumero1
            {
                Titulo = dados["Titulo" + numeroDoProduto],
                Descricao = dados["Descricao" + numeroDoProduto],
                ClienteId = id

            };

            formContent.Add(new StringContent(layout.ClienteId.ToString()), "ClienteId");
            formContent.Add(new StringContent(layout.Titulo), "Titulo");
            formContent.Add(new StringContent(layout.Descricao), "Descricao");

            foreach (var dado in dados.Files)
            {
                Produto produto = new Produto
                {
                    DescricaoProduto = dados["DescricaoProduto" + numeroDoProduto],
                    Preco = float.Parse(dados["Preco" + numeroDoProduto]),
                    LayoutNumero1Id = layout.Id
                };

                formContent.Add(new StringContent(produto.Preco.ToString()), "Produtos["+ i + "].Preco");
                formContent.Add(new StringContent(produto.DescricaoProduto), "Produtos[" + i + "].DescricaoProduto");
                formContent.Add(new StringContent(Path.GetFileName(dado.FileName)), "Produtos[" + i + "].Foto");
                formContent.Add(new StreamContent(dado.OpenReadStream()), "Produtos[" + i + "].FotoFile", Path.GetFileName(dado.FileName));

                numeroDoProduto++;
                i++;
            }

Here is an exemple where i created a layout with two products enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

Sorry if some words in the code are in portuguese but i think that is not relevant to the solution of the problem :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.