Thursday, January 3, 2013

Resolving a content item url in Orchard

Recently I needed to create a link to edit a content item in Orchard. Orchard uses a url like http://mysite/Home/Admin/Contents/Edit/123, where the id corresponds to the content item id.

My first thought was to hand-craft the url, replacing the content id as needed. But I found a better way: use the item's meta-data. Firstly inject the orchard IContentManager as usual, then call IContentManager.GetItemMetadata() The returned ContentItemMetadata contains MVC route's, for my particular case, EditorRouteValues had all the data I needed.

In my exploration of Orchard, I am continually finding myself having to dive into the code to work out how to do things. So here is 'how' I finally stumbled on the meta data solution.

Firstly I knew the Content Control Wrapper performed some 'magic' which added a link to a content item's edit.
Alas so-far I have no special trick for getting from a feature to the code that implements it. But eventually I found Orchard.Core/Contents/ControlWrapper.cs which implements the feature as a IShapeTableProvider. In here we see Content is wrapped with a Content_ControlWrapper shape.

Since nothing particularly enlightening is happening, I went to the view for the shape: Orchard.Core/Views/Content.ControlWrapper.cshtml. In the view the Html.ItemEditLinkWithReturnUrl() caught my eye.

This ItemEditLinkWithReturnUrl() is an extension, tracked down to Orchard.Framework/Mvc/Html/ContentItemExtensions.cs

Navigating to find the core ItemEditLink helper, bingo, I found how the content item meta-data is used for route values.

A short list of C# coding issues.

Injecting services into entities It been bugging me for a while now that to use services in a entity can be a bit of pain. It usually starts...