Instantiates the ViewModel in ok?

For example, I have models: Student

and Course

. Student

It hasList<Course> Courses{get;set;}

All data has already been filled in from the web service

I have Student/Index

one that returns an ActionResult, which takes StudentViewModel

But I also have a Course/Index

View that returns an ActionResult, takesCourseViewModel

This should set the foundation for my question: Ok if I follow this option, which I think is very neat and simple: Create an instance ViewModel

in the Student/Index

View

 @foreach(var course in Model.Courses)
    {
       Html.RenderPartial("path/tocourse", 
        new CourseViewModel{Course = course}) ;
    }

      

Or I need to make StudentViewModel

have List<CourseViewModel>

, so I can have:

@foreach(var courseViewModel in Model.CourseViewModels)
{
       Html.RenderPartial("path/tocourse", courseviewModel) ;
}

      

At first glance, the above may look better, but in action Index

(or whatever) I need to do the following:

 new StudentViewModel{
            CourseViewModels = courses.Select(c=>new CourseViewModel{copy stuff}).ToList()
       } 

      

I hate this and also it might confuse me later or another developer seeing that other indirection gives me access to ie courses StudentViewModel.StudentModel.Courses

.

So which one is the best fit? Surely it can't be so bad to instantiate, ViewModel

or Model

if that's important in View

?

+3


source to share


2 answers


This is normal. This is not considered best practice. The best practice would be to do as little processing or instantiation as possible in your view.

For SOC, I would redefine this code to use Partials with Child Action Methods

Html.Action("path/tocourse");

      



The Child action will instantiate and pass the model, brightening your view.

[ChildActionOnly]
public ActionResult tocourse()
{

courseviewModel model = new courseviewModel();

    return PartialView(model);
}

      

+4


source


Ideally, your view shouldn't have any logic of the viewmodel instance, and the controller should do all of this and render that model. The view must be clean. And the viewmodel should only have the properties you need for the view. You may now have a fairly complex model, but if you find that a particular model is very complex for your view, simply create a view specific to that view with limited properties that your view needs.



0


source







All Articles