Search code examples
sitecoresitecore-mvcsitecore7.1

Sitecore 7.1 MVC Html.Sitecore().Field not giving same result as FieldRenderer.Render


I have a Sitecore 7.1 solution using MVC and am rendering fields using @Html.Sitecore().Field("FieldName", ContentItem). Because I want multiline text fields to render out <br/> tags I have removed the GetTextFieldValue processor from the renderField processor section in web.config using an App_Config\Include patch file as described here: http://laubplusco.net/sitecore-update-bummer/. What I'm finding is that if I use Sitecore.Web.UI.WebControls.FieldRenderer.Render() this produces the output with the line breaks as expected, but if I use the Html.Sitecore().Field() extension method no line break is rendered.

I found that you can write

@Html.Sitecore().Field("FieldName", item, new { linebreaks = "<br/>" })

which seems to do the job.

Is there some other config which needs to be set to make the Field() extension method behave in the same way as FieldRenderer.Render, or do I just have to use the method above?


Solution

  • The implementation of field rendering seems to be different for MVC and WebForms. You can check the code of Sitecore.Web.UI.WebControls.FieldRenderer.RenderField() in .NET Reflector. It adds line breaks for multi-line fields to the RenderFieldArgs, before calling the render field pipeline:

            if (item.Fields[this.FieldName].TypeKey == "multi-line text")
            {
                args.RenderParameters["linebreaks"] = "<br/>";
            }
    

    In @Html.Sitecore().Field(...) the rendering pipeline is called in a similar way, but the rendering arguments are set up differently, "linebreaks" is not added. To make the behavior the same for every rendering you could add your own processor with the same logic as the code above in Sitecore.Web.UI.WebControls.FieldRenderer.RenderField(). Somehow like this:

    public void Process(RenderFieldArgs args)
    {
        Assert.ArgumentNotNull((object)args, "args");
    
        if (args.FieldTypeKey == "multi-line text")
            args.RenderParameters["linebreaks"] = "<br/>";
    }
    

    and add this to your render field pipeline with an include file.