asp.net - Do I need a ViewModel to take 1-to-many-data to the view? -


this basic stuff, can't find clear answer anywhere..

lets i'm doing mvc (3) application entity framework (ef4), , have these 3 classes:

public class foo {     public int fooid     public bar bar     public icollection<baz> bazes }  public class bar {     public int barid     public string bartext }  public class baz {     public int bazid     public foo foo } 

what best way of taking foo's related bar's baz's can loop through foo's , making use of related items? need make viewmodel, , should contain?

what want end like

@model = ienumerable<foo/fooviewmodel>  foreach(var foo in model) {   @if(foo.bar.barid == 1)   {     foreach(var baz in foo)     {       @baz.bazid     }   } } 

you don't need view models. pass ef objects directly view, , in simple crud cases fine. in experience though never simple crud.

i typically need data many places not contained in 1 object. example, might want show/hide data depending on person's role in system. foo wouldn't know that. example form dropdownlist. need pass info somewhere. again, foo doesn't know options should be.

i'd create view model each class , use automapper map domain model view model.

your view model this:

public class fooview{     public barview bar { get; set;}     public icollection<bazview> bazes { get; set;} }  public class barview{     public int barid { get; set; }     public bazview baz { get; set; } }  public class bazview {     public int bazid { get; set; } } 

your action method have in it:

var foos = foorepository.getfoos(); var model = mapper.map<ienumerable<foo>,ienumerable<fooview>>(myfoos); return view(model); 

Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -