ALT text not encoded


Description

The content of an Image field’s ALT text is not HTML-encoded when the Web or XSL Image Control are used.

If the provided ALT text contains invalid characters, the generated HTML is not valid.

Solution

For Web control:

<sc:Image id="imageControl" Field="Image" runat="server" />

Encode the Alt text with the following code:

public void Page_Load(object obj, EventArgs eventArgs)
{
    if(!IsPostBack)
    {
        var imageField = Sitecore.Context.Item.Fields["image"];         
        if(FieldTypeManager.GetField(imageField) is Sitecore.Data.Fields.ImageField)
        {
            string altText = ((Sitecore.Data.Fields.ImageField)imageField).Alt;
            imageControl.Alt = HttpUtility.HtmlEncode(altText);
        }
    }
}

For XSL control:

In the xsl rendering file, replace the <sc:image ... /> tag with the code similar to the following: 

<img src="{sc:fld('Image',.,'src')}" >
  <xsl:attribute name="alt">
    <xsl:value-of select="sc:fld('Image',.,'alt')" disable-output-escaping="yes"/>
  </xsl:attribute>
</img>