Typical scenario in data-centric RIA development is to insert into GridView control a web image corresponding to some "Image_URL" value stored in the data field of underlying database, which is "hyperlinked" to another "Target_URL" also stored in the database. Image OnClick event should open the target web page. In most general case the image could be missing, thus the alternative text should serve as a hyperlinked text. Three different solutions pertinent to ASP.NET GridView control are described below.
1. TemplateField with pair of Hyperlink
field and img
element
Listing 1
<asp:TemplateField>
<itemtemplate>
<asp:HyperLink runat="server" NavigateUrl='<%# Eval("Target_URL") %>' Target="_blank">
<img src="<%# Eval("Image_URL") %>" alt="Read online" />
</itemtemplate>
2. TemplateField with ImageButton
This technique though it provides the minimum coding and fairly robust results is not recommended as it requires the server side "double-trip", thus degrading the responsiveness of RIA and negatively impacting the overall user experience (it's brought here mostly for didactic purpose):
Listing 2
<asp:TemplateField>
<itemtemplate>
<asp:ImageButton runat="server" ImageUrl='<%# Eval("Image_URL") %>' PostBackUrl='<%# Eval("Target_URL") %>' AlternateText="Read online" />
</itemtemplate>
3. TemplateField with ImageButton
and javascript onClick
This method requires some additional Javascript coding, but provides maximum flexibility in terms of formating the target window to be opened on image click event:
Listing 3
<asp:TemplateField>
<itemtemplate>
<asp:ImageButton ID="ImageButton1" runat="server" ImageUrl='<%# Eval("Image_URL") %>'
OnClientClick='<%# String.Format("javascript:return openTargetURL(\"{0}\")", Eval("Target_URL")) %>' AlternateText="Read online" />
</itemtemplate>
Javascript snippet to be added to head
section
This sample Javascript code snippet allows opening target web page in new browser window with customized appearance set programmatically:
<script type="text/javascript">
function openTargetURL(url)
{ window.open(url, "newWindow", "resizable=1,menubar=0,toolbar=0,scrollbars=1"); }
</script>
DEMO
ASP.NET GridView Hyperlinked image technique as described above has been used in Online Music Library: click on the sample snapshot shown below to see the working demo:
Design Notes: Server side Image rendering
Be aware that pertinent to Listing 1, the image is rendered as "img" element, while in two other cases it is rendered as "input type="image" element. Corresponding sample CSS3 code snippets is show below in Listing 4:
Listing 4
<style type="text/css">
img { width:200px; }
input[type="image"] {width:200px; }
</style></img>
Image decoration via HTML5/CSS3
Various aesthetic enhancement techniques, namely single and double borders, borders with inset shadows and color gradients could be applied to the image as described in [1].
References
1.
Add Image Borders using HTML5/CSS3[
^]