I do have pet projects in which I try to get every single nitty gritty detail right. And then it bothers me that by default the ASP.NET Image control adds a style="border-width:0px" to the rendered image tag even though I never asked for it. Not even does it add the style attribe without asking, it doesn't offer a way to get rid of it! You can get rid of it though!
Fortunately ASP.NET does come with control adapters, so we can do something about it. Lets first create a new .browser file in the App_Browser directory to tie up our control adapter to the rendering of the Image control. The contents should like lik this:
<?xml version="1.0" encoding="utf-8" ?>
<browsers>
<browser refID="Default">
<controlAdapters>
<adapter
controlType="System.Web.UI.WebControls.Image"
adapterType="WMB.VirtueleKassa.WebControls.ImageAdapter" />
</controlAdapters>
</browser>
</browsers>
Next thing to do is to create the WMB.VirtueleKassa.WebControls.ImageAdapter. Create a new class file in the App_Code directory. The code for the ImageAdapter should look like this:
!! have a look at the comment of RichardD! He proposed a better solution !!
using System;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.Adapters;
namespace WMB.VirtueleKassa.WebControls {
public class ImageAdapter : WebControlAdapter {
public ImageAdapter() {
}
protected override void RenderBeginTag(HtmlTextWriter writer) {
Image img = this.Control as Image;
if (img.BorderWidth.IsEmpty) {
string origTag = string.Empty;
using (StringWriter sw = new StringWriter())
using (HtmlTextWriter hw = new HtmlTextWriter(sw)) {
base.RenderBeginTag(hw);
hw.Flush();
hw.Close();
origTag = sw.ToString();
}
string newTag = origTag.Replace("border-width:0px;", "");
newTag = newTag.Replace(" style=\"\"", "");
writer.Write(newTag);
}
else {
base.RenderBeginTag(writer);
}
}
protected override void RenderEndTag(HtmlTextWriter writer) {
}
protected override void RenderContents(HtmlTextWriter writer) {
}
}
}
And thats it! If you do apply a width yourself, the tag will be saved, and so will any other style tags. Only if, after the deletion of the border-width:0px; the style attribute remains empty, the complete style attribute will be removed as well. Have a look at the source of this page to see the result.
Regards,
Wesley
Comments have been disabled for this content.