Sitecore MVC Image or Text within Link Field renderer

Wrapping an Image or Text in a link field is a very common use case. In Sitecore WebForms this could be achieved by simply wrapping LinkField renderer around a text field or image field renderer, E.g.

One of the good things about using this technique is that both the link field and the text field are editable in Page Edit mode. Also, the “Link Description” from the link field is not rendered.

In, MVC Razor view I was trying to achieve the same result by using the following code

@Html.Sitecore().BeginField("LinkFIeld", item, new { Parameters = new SafeDictionary<string> { {"default-text",""} } })
                        @Html.Sitecore().Field("TextField", item)

However, it did not work as I had expected. The Link Description along with the Text field value was rendered.

I thought of a few solutions

  1. Customize the Sitecore.Xml.Xsl.LinkRenderer class and its Render() method
  2. Write my own MVC helper
  3. Extend the <renderField> pipeline to handle a new parameter “DisableLinkDescription

After some deliberation I decided to implement the third option.

In my solution,

  1. I added a new processor after GetLinkFieldValue in <renderField>

     <processor patch:after="*[@type='Sitecore.Pipelines.RenderField.GetLinkFieldValue, Sitecore.Kernel']" type="XCore.SitecoreExtensions.Pipelines.RenderField.FixLinkFieldTitle, XCore.SitecoreExtensions" />
  2. My processor is looking for a new parameter “DisableLinkDescription”. If the value is set to true, the pipeline removes link description from args.Result.FirstPart

     public class FixLinkFieldTitle
            public void Process(Sitecore.Pipelines.RenderField.RenderFieldArgs args)
               if ((args.FieldTypeKey == "link" || args.FieldTypeKey == "general link") &&
                    args.Parameters.ContainsKey("DisableLinkDescription") &&
                    MainUtil.GetBool(args.Parameters["DisableLinkDiscription"], false))
                    int indexOfClosingTag = args.Result.FirstPart.LastIndexOf('>');
                    if (indexOfClosingTag > 0 && args.Result.FirstPart.Length > indexOfClosingTag + 1)
                        args.Result.FirstPart = args.Result.FirstPart.Remove(indexOfClosingTag + 1);
  3. Finally, I updated my view

     @Html.Sitecore().BeginField("LinkFIeld", item, new { DisableWebEdit = true, DisableLinkDiscription = true })
                            @Html.Sitecore().Field("TextField", item)

Hope this solution helps you!