How do I mount a List or Ienumerable array in the Controller and move to View?

Asked

Viewed 58 times

0

Good evening! I made a request to my webapi to search for data to use=it in a DropDownlist @Html.DropDownList("Id","Descricao"). In My controller, I can pull Webapi results in collection, I treated Json and I put it in my product class, which only has Id and Description List<Produto>

How do I stop, before returning to the view where I will use this list, to create an Object in the list to link to my view template and use as a dropdown?

1 answer

0

Example of how to do:

public class Pedido {   
     public int ProdutoId {get;set;}    
     public List<Produto> Produtos {get;set;} 
}

on your controller:

public ActionResult ExemploController(){
        var pedido = new Pedido();
        pedido.Produtos.Add(new Produto(){....});
        pedido.Produtos.Add(new Produto(){....});
        pedido.Produtos.Add(new Produto(){....});
}

In your view:

@Html.DropDownListFor(model => model.ProdutoId, new SelectList(Model.Produtos, "Id", "Descrição"), "Selecione")

or

@Html.DropDownList("ProdutoId", 
                    new SelectList(Model.Produtos, "Id", "Descrição"),
                    "Selecione")
  • Just to complement, you have to say which type of your View to bind, in case put something like: @model List<Product>

  • in my case he would have to use "@model Order" and not "@model List<Products>". If he only needs the list, then I would need to change my example

Browser other questions tagged

You are not signed in. Login or sign up in order to post.