1
我试图围绕viewmodels和适当的时候使用它们。我想在这种情况下该怎么做了解释:这种情况下的理想(视图)模型设计
型号:
public class Person
{
public string firstName {set;get;}
public string lastName {set;get;}
public string City {set;get;}
.... other junk
}
控制器:
IEnumerable<Person> model = db.Person
.Where(r => r.City == city)
.Select(r => new Person{
firstName = r.firstName,
lastName = r.lastName,
something = r.something});
现在让我们假设我的页面允许用户选择一个city
,他想过滤。此外,我只想显示firstName
和lastName
。这是使用视图模型的时候吗?以前我会做这样的事情。
视图模型:
public class PersonViewModel
{
public string firstName {set;get;}
public string lastName {set;get;}
public string cityChoice {set;get;}
public IEnumerable<SelectListItem> cityList {set;get;}
}
我来实现,由于我的查询将返回一个类型IEnumerable<Person>
,那么我将不得不通过查询返回的每一行cityList
。更好的视图模型会是什么?我的下一个想法是:把一切的IEnumerable
:
public class PersonViewModel
{
public IEnumerable<string> firstName {set;get;}
public IEnumerable<string> lastName {set;get;}
public IEnumerable<string> cityChoice {set;get;}
public IEnumerable<SelectListItem> cityList {set;get;}
}
这似乎不是一个明智的选择的。它看起来很混乱,实现也看起来像是一种痛苦。
总之,在保持List<SelectListItem>
的同时将最少数量的数据从控制器传递到视图的最佳方式是什么?我已经看到通过viewbag
或viewdata
传递列表的实现,但这似乎是垫练习。提前致谢。
这似乎给了高效的方法。我很好奇,如果有其他方法可以更有效地做到这一点。如果您有许多页面显示表格的唯一子集,该怎么办?你需要每个虚拟机的权利? – Jeff
理想情况下是的..因为否则它开始变得混乱。 – Max