Do I need a ViewModel to take 1-to-many-data to the view?
This is probably basic stuff, but I can't find the clear answer anywhere..
Lets say I'm doing an MVC (3) application with Entity Framework (EF4), and I have these three 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 would be the best way of taking all the Foo's with related Bar's Baz's so that I can loop through the Foo's and making use of the related items? Do I need to make a ViewModel, and what should it contain?
What I want to end up with is somethin开发者_StackOverflow中文版g 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 specifically need view models. You could pass your EF objects directly to your view, and in simple CRUD cases that is fine. In my experience though it is never that JUST simple CRUD.
I typically need to get data from many places that is not all contained in one object. For example, I might want to show/hide data depending on a person's role in the system. Foo probably wouldn't know that. Another example would be a form with a dropdownlist. You need to pass that info somewhere. Again, foo probably doesn't know what the options should be.
I'd create a view model for each class and then use AutoMapper to map the domain model to your view model.
Your view model would look like 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 would have something like this in it:
var foos = fooRepository.GetFoos();
var model = Mapper.Map<IEnumerable<Foo>,IEnumerable<FooView>>(myFoos);
return View(model);
精彩评论