Category : .Net | Author : Chtiwi Malek | First posted : 3/13/2012 | Updated : 9/4/2013
Tags : asp.net, c#,
Triggering and consuming a Postback without an Asp.net control

Triggering and consuming a Postback without an Asp.net control

In one of the projects I'm working on, the client wanted the ability to add a link (a simple anchor) within the text of his products description to download a file from the server (that he will upload when creating or updating the article).

To do that, I thought of using the postback javascript function. the __doPostBack javascript function takes two parameters, the first one is the ID of the control that triggered the postback, and the second one is  "eventArgument" which contains additional data associated with the control.

Here’s what the HTML code that will fire the postback looks like:
... click here to download the product <a href="javascript:__doPostBack('DownFile', '')">Details</a> ...
Of course the framework will not find a control on the page with that ID "DownFile" to bind to, but we will capture the event :
string trgCtrl = Request.Params.Get("__EVENTTARGET");
if (IsPostBack && !string.IsNullOrEmpty(trgCtrl) && (trgCtrl == "DownFile"))
{
  // Here we will send the user a file to download
  Response.AppendHeader("content-disposition", "attachment; filename="+ProdID+".zip");
  Response.ContentType = "application/zip";
  Response.WriteFile(Server.MapPath("~/files/"+ProdID+".ppp"));
  // here some code to update the number of file downloads
  // ... ... ...
}
In this way, the  final user will be able to download the file without leaving the page and without knowing the direct link/url.
Leave a Comment:
Name :
Email : * will not be shown
Title :
Comment :