For example I have the Models:
Student and Course.
Student has a List<Course> Courses{get;set;}
All data is already populated from the web service
I have a Student/Index which returns an ActionResult that takes a StudentViewModel
But I also have a Course/Index View which returns an ActionResult takes a CourseViewModel
That should set the foundation for my question:
Is it alright if I follow this option, which I think is very neat and simple:
Create an instance of a ViewModel in the Student/Index View
@foreach(var course in Model.Courses)
{
Html.RenderPartial("path/tocourse",
new CourseViewModel{Course = course}) ;
}
Or should I make StudentViewModel have a List<CourseViewModel>, so I can have:
@foreach(var courseViewModel in Model.CourseViewModels)
{
Html.RenderPartial("path/tocourse", courseviewModel) ;
}
At first glance, the above might look better, but in the Index action (or whatever) it would require me to do the following:
new StudentViewModel{
CourseViewModels = courses.Select(c=>new CourseViewModel{copy stuff}).ToList()
}
I hate that, and also it could confuse me later on or another developer, seeing that another indirection gives me access to Courses i.e StudentViewModel.StudentModel.Courses.
So which one is better approach? Surely it can’t be that bad to create an instance of a ViewModel or a Model for that matter in a View?
It’s perfectly OK to do this. It’s not considered Best Practice. Best Practice would be to do as little processing or instantiation as possible in your View.
For the sake of SOC, I would re-factor this code to use Partials with Child Action Methods
The Child Action will instantiate and pass the Model, lightening your View.