Entity FrameWork (ORM) and DropDownList Html

1

I have two mapped models that will work like this: The model Afaze will have a ComboBox (DropDownList) that will make the categories available to the user to select, however 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; }


}

In my view I tried something like this: ( But it does not 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")
}
    
asked by anonymous 24.09.2016 / 00:42

1 answer

3

I hope I can help you.

Look at the image below, you may notice that the second parameter is of type IEnumerable<SelectListItem> , however you are passing a IEnumerable<Categorias> .

So,youshouldchangethereinyourAfarámodelthe

publicvirtualICollection<Categorias>Categoria{get;set;}

for

publicvirtualICollection<SelectListItem>Categoria{get;set;}

Then,youmustaddanewfieldinyourAfazermodeltosavetheselectedvalue.Assumingyou'dliketosavetheIdofyourCategory,addthefollowingfieldintheAfazermodel:

publicstringIdCategoria{get;set;}

Thenyoushouldmodifyyourviewtolooklikethis:

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

The first parameter is the field of your Afará form that will be populated when selecting any category.

Finally, in your Action , add as a return a new instance of your model, already populating your IEnumerable , like this:

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" },
           }
     });
}

Okay, now your dropdown will be working. Any questions are available.

Some tips:

I have some tips for your code, however this is only by convention, it does not have to be followed.

  • Class names always in the singular, in your case, the class should be called Category ;
  • Property names of the IEnumerable , ICollection types and etc, always in the plural, in your case, the Category property in the Afazer model should be called Categories ;
  • Model names should contain the word Model in the end, in your case it would be AfazerModel , or better yet, to say that it is a model linked to a View , leave the name as AfazerViewModel ;
  • Remembering that this is just by convention, for better written code, it does not have to be followed

    Well, that's it. Hope this helps. Thanks!

        
    24.09.2016 / 02:12