Frage

How can i set the alt atribute = the filename of an image tag in asp.net automatically without using javascript?

<img src="/a/b/c/xxx.jpg" />

to

<img src="/a/b/c/xxx.jpg" alt="xxx.jpg" />

I tought maybe something like a rewrite module on IIS? Or maybe somehow change the base Image class to emit different html?

Any ideias?

Thanks

War es hilfreich?

Lösung

If you're willing to add the runat="server" attribute to your img tags, then in your code behind you can loop through the list of controls on your page and for all the img tags, update the alt attribute. I wrote this without testing so there may be some minor tweaks required.

private void UpdateImgTags<T>(ControlCollection controlCollection)
where T : Control
{
    foreach (Control control in controlCollection)
    {

        if (control is T)  {
            string filename = (T)control.Attributes["src"];
            filename = IO.Path.GetFileName(filename);
            (T)control.Attributes.Add("alt",filename);
        }
    }
}

To call the method:

UpdateImgTags<HtmlImage>(Page.Controls)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top