Lews Therin
Lews Therin

Reputation: 10995

Is Creating an Instance of a ViewModel in a View ok?

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?

Upvotes: 3

Views: 179

Answers (2)

KKS
KKS

Reputation: 3630

Ideally your view should not have any viewmodel instance logic rather the controller should do all that stuff and give that model to the view. View should be clean. And viewmodel should only have those properties that you need for the view. Now, you can have a model that is complex enough but if you find yourself that a particular model is very complex for your view, just make a viewmodel specific to that view with limited properties that your view needs.

Upvotes: 0

Dave Alperovich
Dave Alperovich

Reputation: 32490

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

Html.Action("path/tocourse");

The Child Action will instantiate and pass the Model, lightening your View.

[ChildActionOnly]
public ActionResult tocourse()
{

courseviewModel model = new courseviewModel();

    return PartialView(model);
}

Upvotes: 4

Related Questions