Just working through a tutorial on asp.net/mvc for the music store application.
Ref: http://www.asp.net/mvc/tutorials/mvc-music-store-part-3
In the controller they are passing a list of genres to the view model, I am just a beginner but I feel like it is the viewmodel’s job to present the data in what ever format the view requires.
the tutorial code does this…
public ActionResult Index()
{
// Retrieve list of Genres from database
var genres = from genre in storeDB.Genres select genre.Name;
// Set up our ViewModel
var viewModel = new StoreIndexViewModel()
{
Genres = genres.ToList(),
NumberOfGenres = genres.Count()
};
// Return the view
return View(viewModel);
}
What I want to do is pass genres to the viewModel and inside the viewModel create the list as well as set the NumberOfGenres property. The way this is coded the controller has to know more about the view than it needs to.
can someone show me what my viewModel class would look like in order to use the ToList() and Count() methods on the genres property inside my viewModel ?
I’m going to disagree with you. The controller knows nothing about the view, only the model. The view model, IMO, should be a simple container just as it is in the tutorial. It’s the controller’s job to fill up the container with data and pass it off to the view.
It’s an open question whether the view model is as simple as it needs to be, i.e. you can easily derive the number of genres from the list of them so it’s not really necessary to have it as a separate property. If you wanted to just have the list stored in the model, all you would have to do is invoke the Count() method in the view instead of doing it in the controller.
Not knowing the tutorial, I’m not sure whether they’ve done it this way in anticipation of adding paging to the model, however. If you did want to support paging in the model, then you would want the total count as a separate property since you’d only be passing part of the collection to the view.