Creating a query string when clicking on image (as

2019-09-03 14:55发布

问题:

My application is an image gallery and with a Repeater control i'm listing the thumbnails (that's in a separate folder, apart from the full scale images). When clicking on a thumbnail a full scale image should be shown in the Image control "fullSizeImage" and a query string should be created which (with a GET of the page) shows that specific image in full scale.

The code for the query string is done, but the problem is that I don't have a clue where to put it (the creation of the query), because the HyperLink control doesn't support event clicks. Is there a way to use for example Repeater ItemCommand, or how could I accomplish what I want here?

Thanks!

from default.aspx:

<asp:Image ID="fullSizeImage" runat="server" />

    <asp:Repeater ID="ImageRepeater" runat="server" DataSourceID="" >
        <ItemTemplate>
            <asp:HyperLink ID="ImageHyperLink" NavigateUrl='<%# Eval("Name", "~/Images/{0}") %>' runat="server" CssClass="thumbnails" >
                <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Name", "~/Images/Thumbnails/{0}") %>' CssClass="thumbnail" />
            </asp:HyperLink>
        </ItemTemplate>
    </asp:Repeater>

from code behind:

protected void Page_Load(object sender, EventArgs e) {

    var directory = new DirectoryInfo(Gallery.PhysicalApplicationPath + "/Images");
    var theFiles = directory.GetFiles();

    ImageRepeater.DataSource = theFiles;
    ImageRepeater.DataBind();

    var dataName = Request.QueryString["name"];
    fullSizeImage.ImageUrl = dataName;
}

the creation of the query string (that I don't know where to put):

string str = ImageUrl; <- the url of the clicked image
Response.Redirect("default.aspx?name=" + Server.UrlEncode(str);

回答1:

This works with me

<asp:HyperLink ID="ImageHyperLink" NavigateUrl='<%# "~/default.aspx?name=" + Server.UrlEncode(Eval("Name","~/Images/{0}")) %>' runat="server" CssClass="thumbnails" >
    <asp:Image ID="Image1" runat="server" ImageUrl='<%# Eval("Name", "~/Images/Thumbnails/{0}") %>' CssClass="thumbnail" />
</asp:HyperLink>


回答2:

In the code behind you can set up a method tied to the Repeater's ItemDataBound event. In that method you can retrieve the current file, find the HyperLink, and set the link's NavigateUrl to be the string you are generating. Something like the following:

ImageRepeater.ItemDataBound += new RepeaterItemEventHandler(ImageRepeater_ItemDataBound);

private void ImageRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    [File] f = (File)e.Item.DataItem;
    HyperLink ImageHyperLink = (HyperLink)e.Item.FindControl("ImageHyperLink");
    string str = f.ImageUrl;
    ImageHyperLink.NavigateUrl = "default.aspx?name=" + Server.UrlEncode(str);
}