View model with ICollection

0

I'm starting in mobile development and I'm doing a category control system. Where I can multi-level categories.

My entity looks like this:

public int CategoriaId { get; set; }
public string Descricao { get; set; }
public int? CategoriaPaiId { get; set; }
public virtual Categoria CategoriaPai { get; set; }
public virtual ICollection<Categoria> CategoriasFilho { get; set; }

My question is when creating my ViewModel

I started programming and so far it's like this:

    [Key]
    public int CategoriaId { get; set; }

    [Display(Name = "Categoria pai")]
    public string CategoriaPaiId { get; set; }


    [Display(Name = "Descrição da categoria")]
    [Required(ErrorMessage = "Descrição obrigatória.")]
    public string Descricao { get; set; }

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

How can I complete this?

    
asked by anonymous 24.08.2016 / 16:01

1 answer

1

Separation in ViewModels is only required if the presentation data in Views is different from what is proposed in Model . That is, if your Model looks like this:

public int CategoriaId { get; set; }
public string Descricao { get; set; }
public int? CategoriaPaiId { get; set; }
public virtual Categoria CategoriaPai { get; set; }
public virtual ICollection<Categoria> CategoriasFilho { get; set; }

You just need to decorate it like you did with your ViewModel , and this can still be improved:

[Key]
public int CategoriaId { get; set; }

[Display(Name = "Categoria pai")]
public int? CategoriaPaiId { get; set; }

[Display(Name = "Descrição da categoria")]
[Required(ErrorMessage = "Descrição obrigatória.")]
public string Descricao { get; set; }

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

public virtual Categoria CategoriaPai { get; set; }
public virtual ICollection<Categoria> CategoriasFilho { get; set; }

It's okay to expose a Model in View . To protect which fields can be defined, use the [Bind] with Include :

[HttpPost]
public async Task<ActionResult> Criar([Bind(Include = "Descricao,CategoriaPaiId")] Categoria categoria) { ... }

Or, if it is easier, Exclude :

[HttpPost]
public async Task<ActionResult> Criar([Bind(Exclude = "CategoriaId,CategoriaPai,CategoriasFilho")] Categoria categoria) { ... }
    
24.08.2016 / 19:24