Search code examples
asp.netimageaccessibility

Server-side image tags with empty alt attribute


In ASP.Net is there a way to get the alt attribute of server-side image tags to render with an empty value? Preferably without creating a new derived class?

In order to pass accessibility tests, I need to add alt="" to images where they are purely decorative and there is no purpose for text to be read-out by screen readers.

But both of the following result in the alt tag being ommitted, making the image fail the accessibility checks...

<img runat="server" src="~/myimage.jpg" alt="" />
<asp:Image runat="server" ImageUrl="~/myimage.jpg" AlternateText="" />

This is the rendered HTML...

<img src="myimage.jpg" />
<img src="myimage.jpg" style="border-width:0px;" />

Solution

  • ASP Image class includes a GenerateEmptyAlternateText property for this.

    By default, when the AlternateText property is not set, the Image control does not include the alt attribute to specify the alternate text in the control rendering. Set the GenerateEmptyAlternateText property to true to always include the alternate text attribute in rendered output for the Image control.

    The XHTML document type definition requires the alt attribute on image controls. However, accessibility best practices recommend that image controls that do not convey information relevant to the context of the Web page should not specify an alt attribute. You can meet both XHTML and accessibility requirements by setting the GenerateEmptyAlternateText property to true.

    Note: Alt and AlternateText are empty string by default and can be omitted when GenerateEmptyAlternateText="True"

    <asp:Image runat="server" ImageUrl="~/myimage.jpg" GenerateEmptyAlternateText="true" />
    

    generates

    <img src="myimage.jpg" alt="">