Entity Framework (ORM) and Dropdownlist Html

Asked

Viewed 114 times

1

Have two models we map that will work like this : The model Afazer will have a Combobox(Dropdownlist) which will make available the categories for the user to select, but these categories are registered by the same, so in the source I have something like this :

 public class Afazer
{
    public int Id { get; set; }

    [Required(ErrorMessage = "Digite a titulo!")]
    [MinLength(1, ErrorMessage = "O tamanho mínimo da titulo são 1 caracteres.")]
    [StringLength(30, ErrorMessage = "O tamanho máximo são 30 caracteres.")]
    [Display(Name = "Titulo: ")]
    public string AFZ_TITULO { get; set; }

    [Required(ErrorMessage = "Digite a descrição!")]
    [MinLength(5, ErrorMessage = "O tamanho mínimo da descrição são 5 caracteres.")]
    [StringLength(256, ErrorMessage = "O tamanho máximo são 256 caracteres.")]
    [Display(Name = "Descrição: ")]
    public string AFZ_DESCRICAO { get; set; }

    [Display(Name = "Nivel de Prioridade")]
    [Range(1, int.MaxValue, ErrorMessage = "Selecione um Nivel valido!")]
    public Prioridades AFZ_NIVEL { get; set; }

    [Display(Name = "Categoria: ")]
    public virtual ICollection<Categorias> Categoria { get; set; }

    [Display(Name = "Status: ")]
    public bool AFZ_DONE { get; set; }

    [Browsable(false)]
    public string ApplicationUserId { get; set; }


}


 public class Categorias
{
    public int Id { get; set; }
    [Required(ErrorMessage = "Digite a categoria!")]
    [MinLength(1, ErrorMessage = "O tamanho mínimo da categoria são 1 caracteres.")]
    [StringLength(15, ErrorMessage = "O tamanho máximo são 15 caracteres.")]
    [Display(Name = "Titulo: ")]
    public string CAT_DESCRICAO { get; set; }
    public string ApplicationUserId { get; set; }


}

Already in my View I tried something like this:(But it doesn’t work)

@model Teste.Models.Afazer

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()
    
    <div class="form-horizontal">
        <h4>Afazer</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
 <div class="form-group">
            @Html.LabelFor(model => model.Categoria, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownList("CAT_DESCRICAO", new SelectList(Model.Categoria.AsEnumerable()))
                @Html.ValidationMessageFor(model => model.Categoria, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

1 answer

3


I hope I can help you.

Note the image below, in it you can notice that the second parameter is of type IEnumerable<SelectListItem>, but you’re passing a IEnumerable<Categorias>.

inserir a descrição da imagem aqui

So you should change there in your model Do the field

public virtual ICollection<Categorias> Categoria { get; set; }

for

public virtual ICollection<SelectListItem> Categoria { get; set; }

then you must add a new field in your model Do to save the selected value. Assuming that you would like to save the Id of his Category, add the following field (in the Afazer model):

public string IdCategoria { get; set; }

then you must modify your view to look like this:

@Html.DropDownList("IdCategoria", Model.Categoria)

The first parameter is your form field Do which will be filled in when selecting a category.

Finally, in his Action, add as return, a new instance of your model, already filling your Ienumerable, in this way:

public virtual ActionResult Index() {
     return View("Index", new Afazer {
           Categoria = new[] {
               new SelectListItem { Text = "Categoria 1", Value = "1" },
               new SelectListItem { Text = "Categoria 2", Value = "2" },
           }
     });
}

Ready, now your dropdown will be working. Any questions I am at your disposal.

Some tips:

I have some tips for your code, but this is only by convention, it doesn’t need to be followed.

  1. Class names always in the singular, in your case, the class should be called Category;
  2. Names of type properties Ienumerable, Icollection etc, always plural, in your case, the Category property in the Afazer model, should be called, Categories;
  3. Model names should contain the word Model in the end, in your case Dozermodel, or better yet, to say that he is a model linked to a View, leave the name as Afazerviewmodel;

Remembering that this is only by convention, for a better written code, does not need to be followed

Well, that’s it. I hope I helped. Thanks!

  • Great explanation, you’re awesome!

  • Thanks! I’m glad it worked out!

Browser other questions tagged

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