Orchard CMS: Using A Static ViewModel For Your Driver Display Method

20 March 2013

If you look at all the documentation about rendering shapes in Orchard, you'll see that while the Model for the partial view gets specified for the Editor methods (via shapeHelper.EditorTemplate()), all the examples I came across for Display relied on a dynamic method and generated model. For example:

 protected override DriverResult Display(
            MapPart part, string displayType, dynamic shapeHelper)
            return ContentShape("Parts_Map",
                                () => shapeHelper.Parts_Map(
                                      Longitude: part.Longitude, 
                                      Latitude: part.Latitude));

The code above results in a generated model being passed to the view partial, with two properties Longitude and Latitude.

But what if you've already got a ViewModel you had in mind for use? I don't think it's documented (yet), but if you take a look in CoreShapes.cs, you'll find where EditorTemplate is implemented, along with its friends, DisplayTemplate() and Partial(). These methods accept a model parameter, so you can happily pass in your view model. Like the EditorTemplate method, DisplayTemplate expects to find the partial view in /Views/DisplayTemplates/, but Partial searches from the base View folder.

  protected override DriverResult Display(MyPart part, string displayType, dynamic shapeHelper)

        MyPartViewModel model = new MyPartViewModel();

        return ContentShape("Parts_MyPart",                                      
            () => 
                return shapeHelper.Partial(                         
                      TemplateName: "Parts/MyPart",     
                      Model: model);


The above code will pass the MyPartViewModel through to /Views/Parts/MyPart.cshtml, easy as that.

Tags: driver, Orchard, ViewModel

Add a Comment

No Comments