How do I create a DropDownList for MVC5 ASP.NET

1

Hello, I'm having difficulty making a Dropdownlist, I have 3 classes an Entities to have relationship with the bank, a Genre that is associated with the Work class.

[Table("Generos")]
public class Genero
{
    [Key]
    public int GeneroId { get; set; }

    public string NomeGenero { get; set; }

    public string Descricao { get; set; }

    public List<Obra> Obras { get; set; }
}


[Table("Obras")]
public class Obra
{
    [Key]
    public int ObraId { get; set; }

    public string NomeObra { get; set; }

    public string Autor { get; set; }

    public string Editora { get; set; }

    public string DescricaoObra { get; set; }

    public int GeneroId { get; set; }
}

I'm not able to do DropDownList, is there any way to do that?

    
asked by anonymous 21.09.2017 / 04:03

1 answer

0

Come on ...

As you have very little information in the question, I will presume some things, in order to set up an example that may be useful for you.

I'll give you a hint of how you can create your DropDownList there are other ways to create, but I'll suggest the way I do.

I'll assume that Genero has several works, so its models will look like this:

[Table("Generos")]
public class Genero
{
    [Key]
    public int GeneroId { get; set; }

    public string NomeGenero { get; set; }

    public string Descricao { get; set; }

    public virtual ICollection<Obra> Obras { get; set; }
}

[Table("Obras")]
public class Obra
{
    [Key]
    public int ObraId { get; set; }
    public int GeneroId { get; set; }

    public string NomeObra { get; set; }

    public string Autor { get; set; }

    public string Editora { get; set; }

    public string DescricaoObra { get; set; }

    public virtual Genero Genero { get; set; }
}

Thus, your% w /% w / w% will look like this:

  public ActionResult Create()
  {
      //Aqui preenche-se uma ViewBag para usar na View
      ViewBag.Generos = db.Generos.ToList();
      return View();
  }

And your% of Create will look like this:

 <div class="col-md-3">
    <label class="control-label">Status</label>
    @Html.DropDownListFor(model => model.ObraId, ((IEnumerable<Genero>)ViewBag.Generos).Select(option => new SelectListItem
    {
       Text = option.NomeGenero,
       Value = option.GeneroId.ToString(),
       Selected = (Model != null) && (Model.ObraId == option.GeneroId)
    }), "Selecione um Gênero...", new { @class = "form-control", @placeholder = "Genero" })
 </div>

In doing so, in the creation of a work you can choose which genre it belongs to.

    
22.09.2017 / 01:36