I’m trying to wrap my brain around viewmodels and when it is appropriate to use them. I’d like an explanation of what to do in this situation:
Model:
public class Person
{
public string firstName {set;get;}
public string lastName {set;get;}
public string City {set;get;}
.... other junk
}
Controller:
IEnumerable<Person> model = db.Person
.Where(r => r.City == city)
.Select(r => new Person{
firstName = r.firstName,
lastName = r.lastName,
something = r.something});
Now let’s say my page allows a user to select a city that he would like to filter by. Additionally, I only want to display the firstName and lastName. Would this be the time to use a viewmodel? Previously I would have done something like this.
Viewmodel:
public class PersonViewModel
{
public string firstName {set;get;}
public string lastName {set;get;}
public string cityChoice {set;get;}
public IEnumerable<SelectListItem> cityList {set;get;}
}
I’ve come to the realization that since my query would return a type IEnumerable<Person>, then I would have a cityList for each row returned by the query. What would the better viewmodel be? My next thought is to make everything an 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;}
}
This doesn’t seem like a smart choice at all. It just looks messy and implementation also look like it could be a pain.
In short, what is the best way to pass the least amount of data from a controller to a view while maintaining a List<SelectListItem>? I have seen implementations where the list is passed via viewbag or viewdata but that seems like pad practice. Thanks in advance.
I would do TWO view models – one for the view, one for the data:
Additionally the second view model for the People specific data: