In this post, we will learn How to Replace broken image with a default image using JavaScript In ASP.NET solution.
In the previous article “Read BLOB data in Oracle DB In ASP.NET“, we have explained How to retrieve BLOB Field from Oracle DB via ASP.Net to show the employee images from the oracle database in the SharePoint portal.
But I had noticed that if an employee does not have an image in the database, the profile image will be shown as a broken image as shown below:
So here, we will show how to replace broken image with a default image using CSS or JavaScript In ASP.NET by doing the following:
Replace broken image CSS
Unfortunately , there is no CSS property that you can use to replace broken images, instead you should use the JavaScript as we mentioned in the coming section.
Replace broken image JavaScript
Steps
- Open your solution using Visual Studio.
- Add your default images to your solution.
- In Front-code, specify which image tag that holds the user profile image.
<img id=”EmpImg” src=”ShowImage.ashx?Account=<%=Request.QueryString["Account"]%>” alt=”" width=”100px” height=”100px” style=”float:right”/>
- In <Img> tag, add the below onError event with the default image URL that you would like to be shown in case the image is broken.
onError="this.onerror=null;this.src='images/User-Administrator-Blue-icon.png';"
- Finally, the <img> tag should looks like the below one
<img id="EmpImg" src="ShowImage.ashx?Account=<%=Request.QueryString["Account"]%>" onError="this.onerror=null;this.src='images/User-Administrator-Blue-icon.png';" alt="" width="100px" height="100px" style="float:right"/>
Conclusion
In conclusion, we have learned how to replace broken image with a default image using JavaScript by adding “onerror” event that would fire and replace the broken image with the specified default image URL.