Steps for downloading a file attached to a gridview

It seems like I'm overlooking something quite straightforward.

I am creating binary files that I am associating with a GridView.

    FileDownloadGrid.DataSource = downloadList;
    FileDownloadGrid.DataBind();

The part of the grid that interests me is written in the following way:

    <asp:TemplateField>
       <ItemTemplate>
         <asp:LinkButton ID="DownloadFile" runat="server" Text="Download" CommandName="DownloadFile1"
           CommandArgument='<%#Eval("FullName") +"|" + Eval("Name") %>'> 
         </asp:LinkButton>
       </ItemTemplate>
     </asp:TemplateField>

I am trying to implement the IFRAME Ajax approach for downloading the file.

function InitializeRequest(sender, args) {
  // Ensure that this async postback is actually
  //   requesting the file download.
  if (sender._postBackSettings.sourceElement.id == "FileDownloadGrid") {
    // Create an IFRAME.
    var iframe = document.createElement("iframe");

    // Get the desired region from the dropdown.
    var fName = $get("CommandArgument").value;

    // Point the IFRAME to GenerateFile, with the
    //   desired region as a querystring argument.
    iframe.src = "Default2.aspx?fName=" + fName;

    // This makes the IFRAME invisible to the user.
    iframe.style.display = "none";

    // Add the IFRAME to the page.  This will trigger
    //   a request to GenerateFile now.
    document.body.appendChild(iframe);
  }
}

Based on my research, it seems like I cannot access the CommandArgument on the client side, and I am struggling to figure out how to obtain the 'FullName' in the script.

Could someone please guide me in the right direction? I am getting quite frustrated with something that should be relatively straightforward.

Thank you

Gene

Answer №1

After much contemplation, I made the decision to directly call the JavaScript function.

Below is the JavaScript code:

function DownloadFile(filename) {
    // Check to be sure this async postback is actually
    // Create an IFRAME.

    var iframe = document.createElement("iframe");
    // Point the IFRAME to GenerateFile, with the
    //   desired region as a querystring argument.
    iframe.src = "Default2.aspx?fileName=" + filename;

    // This makes the IFRAME invisible to the user.
    iframe.style.display = "none";

    // Add the IFRAME to the page.  This will trigger
    //   a request to GenerateFile now.
    document.body.appendChild(iframe);
}

Here is the code that successfully worked for me:

<asp:LinkButton ID="DownloadFile" runat="server" Text="Download"  
   onClientClick='<%# string.Format("DownloadFile(\"{0}\");", Eval("FullName")) %>'></asp:LinkButton>

One important point was converting the 'FullName' path from having backslashes to forward slashes.

string serverPath = toFileName.Replace("\\", "/");

In the default2.aspx.cs file, I implemented the following:

protected void Page_Load(object sender, EventArgs e)
{
  string workPath = Request.QueryString["fileName"];
  string fullPath = workPath.Replace('/', '\\');
  string fileName = Path.GetFileName(fullPath);
  string attachmentHeader = String.Format("attachment; filename={0}", fileName);
  Response.AppendHeader("content-disposition", attachmentHeader);
  Response.ContentType = "application/octet-stream";
  Response.WriteFile(fullPath);
  Response.End();
}

There may be a more efficient way to accomplish all of this, but this was my solution after experimenting and I hope it can benefit someone else.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Changing the information of objects stored in arrays using React Three Fiber

My challenge is with an array of roundedBox geometry shapes called myShape. I am trying to figure out if it's possible to change the position of one of the shapes within the array without creating a new shape altogether. Ideally, I would like to updat ...

Converting a stringified array object to an object using Expressjs

When working with Angular, I am sending stringified data using FormData. Here is an example: this.formData.append('data', JSON.stringify(this.collections)) Now my challenge is converting this string back to an object in my Express backend. The d ...

Tips for accessing the "data" of a PHP array using AJAX

My code snippet using Ajax: $.ajax({ type: 'post', url: 'url.php', dataType: 'JSON', success: function(data) { id = // Need to extract the ID data from 'data' } }); ...

Is there a way to dynamically append options to a Bootstrap selectpicker?

I'm attempting to design a dropdown feature that, when activated by clicking on the first list item, displays a new list of related items next to the initial selection. Here's an illustration: https://i.sstatic.net/fMxAj.png My approach involve ...

Issue with OnChange event in HTML and Adding Content with Jquery

I'm currently working on an app that includes a dynamic dropdown feature using jQuery and the append() method to display changing numbers dynamically. Everything seems to be functioning well in the first field of the form, but when I try to add more f ...

Is there a way to arrange list items to resemble a stack?

Typically, when floating HTML elements they flow from left to right and wrap to the next line if the container width is exceeded. I'm wondering if there's a way to make them float at the bottom instead. This means the elements would stack upward ...

What is the best way to group an array based on a dynamic key?

My goal is to group values in an array by a given ID. I've attempted a method for this, but it's not working for dynamic keys. Here is the current array: let employees = [{"employeeDetail": [{"empID": "XXYYZZ11"," ...

The onClick event cannot be triggered within a div that is generated dynamically

I am having an issue with a jquery code that dynamically generates a div. The problem I'm facing is that the onclick function for the anchor tag is not calling the required function. Below is the code snippet: $("#new").append(' <ul cla ...

Stop Form Submission in Bootstrap 5

I require assistance with identifying the issue in the JavaScript code provided below. I am working with a Bootstrap 5 form where the submission is not being prevented if the fields are left blank or invalid. While the HTML/CSS validation works correctly f ...

Effortless glide while dragging sliders with JavaScript

In the code below, an Object is looped through to display the object key in HTML as a sliding bar. jQuery(function($) { $('#threshold').change(updateThreshold); function updateThreshold () { var thresholdIndex = parseInt($(&apos ...

Bootstrap datepicker not applying datepicker-options as expected

I have been trying to pass all my options in a JSON file according to the instructions on http://angular-ui.github.io/bootstrap/#/top, but unfortunately, I haven't been able to get it to work. I've been experimenting with the Plunkr provided on t ...

Do you have any recommendations for a jQuery plugin that can create a sleek horizontal scrolling image gallery?

Recently, I came across the Smooth div scroll plugin developed by Thomas Kahn, and it fits my requirements perfectly. However, I have encountered a bug that seems to be persisting. The issue arises when both mousewheel scroll and touch scroll are enabled s ...

Implementing a django like feature using ajax requests

I am currently working on a template where I have a link for my article: <div id="voteUp"> <h4><a href="{% url "vote_up" article.id %}">Like {{article.up_vote}}</a></h4> </div> My goal is to increase the vote count for ...

Removing tab panels within a tab container dynamically in asp.net with the help of vb.net

Currently, I am in the process of developing a chat application using asp.net. My goal is to dynamically create tab panels within a tab container for each user accessing the system. Whenever a new user is selected, a corresponding tab with two text boxes ...

Unable to load PHP code using ajax when scrolling to the bottom of the page on an iPhone device

My AJAX function triggers when the user reaches the bottom of the page, loading a PHP script. However, on iPhone, it repeatedly loads the same script (loading id #5, then continuously loading id #4 - while on PC it loads id #5 through to id #1.) index.php ...

The player remains unchanged

Hi, I am currently working on my app to update a player's age. To start off, I have added three players: const playerOne = store.dispatch(addPlayer({ firstName: 'Theo', lastName: 'Tziomakas', position: 'Goakeeper ...

Tips for breaking apart elements of a JavaScript array when a specific delimiter is present in an object property

I am facing a challenge with an array of objects where some properties contain commas. My goal is to split these properties into new objects and recursively copy the rest of the properties into new array elements. For example, consider this original array ...

What is the best way to keep my layout component fixed in the Next13 app directory?

I am struggling to develop a custom layout component that can retrieve its own data. Despite adding 'cache: 'force-cache'' to the fetch function, the updated content from my CMS is still being loaded every time I refresh the page. Below ...

Having difficulty updating a web page while utilizing setInterval() and passing a function that utilizes document.write to display JavaScript content on the page

At the core of my issue lies a blank HTML page that incorporates a JavaScript file, with the following code in the JavaScript file: function doIt() { document.writeln("asdf"); } // Alternatively, you can use setTimeout setInterval("doIt()", 5000); Upon ...

What steps can I take to ensure that my bot disregards any actions taken by other bots?

I need assistance with configuring my bot to ignore certain actions by other bots and prevent logging them. Below is the snippet of my code: let messagechannel = oldMember.guild.channels.find(r => r.name === config.logsChannel); if (!messagecha ...