views:

198

answers:

2

Hello,

I thought that this was easier…

I have a asp:hyperlink control, with target=”_blank”, pointing to the file I want the user to download. My plan is to track the number of times, the users click on this link.

I thought in placing it in ajax update panel, to catch the postback and avoid full page refresh.

However, hyperlink doesn’t have a onClick method.

On the other hand I could use a linkbutton, which has a onClick built in. But It’s harder to make the file open in a new window… and I would also have to do something like:

Response.AppendHeader("Content-Disposition","attachment; filename=myImage.jpg");

But I heard that the above approach has some problems with PPT, PPTX, PPS, PPSX…

What is you'r opinion on this? How and why, would you do it?

+3  A: 

You might want to implement an IHttpHandler to track your downloads, as shown in this article for example.

Basically your handler's ProcessRequest() method would look something like this:

public void ProcessRequest(HttpContext context)
{
    string file = context.Request.QueryString["file"];

    // set content type and header (PDF in this example)
    context.Response.ContentType = "application/pdf";
    context.Response.AddHeader(
         "Content-Disposition", "attachment; filename=" + file);

    // assuming all downloadable files are in ~/data
    context.Response.WriteFile(Server.MapPath("~/data/" + file));
    context.Response.End();
}

Then your hyperlink to download a file would be like this:

<a href="/MyApp/MyHandler.ashx?file=someFile.pdf">...</a>
M4N
im going to take a look at it, and ill get back to you in no time. thank you. (I have slightly updated my question)
Marco
It's a good idea to serve the file through your code anyway. If you provide a direct link you miss counting people who download the file without clicking the link. Also, this allows you limit access to the file, or store the file in some other system (DB, S3, etc.). The issues with special file types that you want IE or other browsers to handle natively can be overcome.
Joel Potter
+1  A: 

You can add an onclick to an asp hyperlink like so:

aHyperlinkControl.Attributes.Add("onclick", "jsCallToSendCountToServer();");
jball
yes, but this would cause a full postback... and i would have to use a ajax update panel or something... right?
Marco
Nope. With a hyperlink control, it will not postback. It's really just going to be a simple HTML hyperlink.
Larsenal
It should be clarified that this is a client-side click event, not a server-side click event. You will need to write a javascript handler which submits the event to some server action in order to use this.
Joel Potter
Exactly - I meant for `jsCallToSendCountToServer()` to imply that. However, Martin's solution seems preferable to me if your looking for a more robust solution.
jball