我是否需要 ViewModel 才能将一对多数据传输到视图中?
这可能是基本的东西,但我在任何地方都找不到明确的答案。
假设我正在使用实体框架(EF4)做一个 MVC (3) 应用程序,并且我有这三个类:
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
}
最好的方法是什么将所有 Foo 与相关 Bar 的 Baz 一起获取,以便我可以循环 Foo 并利用相关项目?我是否需要创建一个 ViewModel,它应该包含什么?
我想要的结果是这样的
@model = IEnumerable<Foo/FooViewModel>
foreach(var foo in model)
{
@if(foo.Bar.BarID == 1)
{
foreach(var baz in foo)
{
@baz.BazID
}
}
}
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 something like
@model = IEnumerable<Foo/FooViewModel>
foreach(var foo in model)
{
@if(foo.Bar.BarID == 1)
{
foreach(var baz in foo)
{
@baz.BazID
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您并不特别需要视图模型。您可以将 EF 对象直接传递到您的视图,在简单的 CRUD 情况下这很好。但根据我的经验,它从来都不是那么简单的 CRUD。
我通常需要从许多地方获取数据,这些数据并不全部包含在一个对象中。例如,我可能想根据一个人在系统中的角色来显示/隐藏数据。 Foo可能不会知道这一点。另一个例子是带有下拉列表的表单。您需要将该信息传递到某处。同样,foo 可能不知道选项应该是什么。
我将为每个类创建一个视图模型,然后使用 AutoMapper 将域模型映射到您的视图模型。
您的视图模型将如下所示:
您的操作方法将包含如下内容:
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:
Your action method would have something like this in it: