Orchard CMS Tips

for developer who want to learn about OrchardCMS

OrchardCMS Tip 1 – Returning a ShapeResult from a Controller Action in a Module

Sometimes you want to write a controller action for a content part you’ve created to handle some kind of behaviour on the front end. However the Driver in Orchard only supports the read-only Displaymethod for the front end.

So what do you do when you want to edit or process information submitted from the front end? That’s where the controller comes in handy.

1. Creating a controller

To create a controller first create a Controllers folder in your module project. Then create a new controller class in this folder. e.g. HomeController. This is just a standard ASP.NET MVC controller which inherits from System.Web.Mvc.Controller.

2. Returning a ShapeResult

The ShapeResult class is actually a ViewResult. It inherits from System.Web.Mvc.ViewResult.

This is where the beauty of Orchard comes in. We don’t have to create a ViewModel class here. Instead we can construct a class using the dynamic object (new in .NET 4.0) and return that to our view instead. And that’s exactly what ShapeResultis for.

Say, for example we want to display a link on our view. We could construct a shape like so and return it from our controller action:

 [Themed] public ActionResult ShowLink() { var linkShape = _shapeFactory.Parts_Link( Url: "https://orchardcmstips.wordpress.com", Text: "OrchardTips Blog", OpenInNewWindow: true ); return new ShapeResult(this, linkShape); }

Note the [Themed] attribute. This tells Orchard to render the shape using the current theme of the site the module is running in.

Also note there is a constructor dependency on _shapeFactory which is of type Orchard.DisplayManagement.IShapeFactory. This interface has been cast to dynamic so that we can define the Parts_Link method on it.

private readonly dynamic _shapeFactory; public HomeController(IShapeFacotry shapeFactory) { _shapeFactory = shapeFactory; }

Orchard will now detect that the shape returned from the ShowLink() method is named Parts_Link and look for a view to display it called Parts.Link.cshtml.

So, in a nutshell that’s how you can use a controller to display shapes in Orchard.

Of course you would normally accept some input data to the action method and do some processing before returning the shape but you should get the idea.

Welcome to Orchard CMS Tips

As I’ve been looking into OrchardCMS for a while now I thought I’d set up a blog to share tips and tricks (mainly for developers) as I discover them.

I hope you find the site useful.