Kneta_
Kneta_

Reputation: 403

Purpose of viewmodel in controllers when data already present

What is the point in using a viewmodel when all the relevant data is already available through the parameter in the signature of the controller? I've seen a lot of examples similar to this:

public ActionResult Index(BasicPage currentPage)
    {
        var model = new BasicViewModel { Heading = currentPage.Heading, Body = currentPage.MainBody, MyBlock = currentPage.MyBlock };
        return View(model);
    }

Why not just send in the "currentpage" in this example directly to the View? Is there something that is considered bad practise by doing like that?

The above was a general question for asp.net-mvc. I'll add a question about Episerver as well here as well and if I'm lucky someone can answer that as well.

When looking through the Alloy site done with MVC I also saw similar behavior like above where a viewmodel is created in all controllers, why not just send in the Page that is sent into the controller directly to the View? It seems like an unnecessary step to create the viewmodel? Most likely I'm missing some important point here =)

Upvotes: 0

Views: 403

Answers (2)

Rob West
Rob West

Reputation: 5241

The idea behind viewmodels is that they are optimised for presentation. If you use domain objects you end up having to put logic into the view itself to control the way things are displayed. Putting logic into the view is poor design so the viewmodel gives you some flex so that you have this logic managed in a more appropriate place.

In addition, you can make your viewmodel simpler, only including the fields that are required for the specific view.

Upvotes: 1

Johan Kronberg
Johan Kronberg

Reputation: 1086

Your code example is not a good idea I agree. But having a view model is a good pattern. You might not need it right away but having a view model available and in place is a good option to have for upcoming additions. I would go with Joel's concept from his MVC templates: http://world.episerver.com/Download/Items/EPiServer-CMS/EPiServer-7---CMS/EPiServer-7-MVC-Templates/

Upvotes: 1

Related Questions