Extend GridView cell for file preview and download

Within my gridview, there is a column labeled "File Name" which includes the names of various files. I am looking for a way to click on a specific file name and be able to view its content as well as save or download the file.

I am open to all suggestions and approaches for achieving this functionality.

_________________________________________
|                        |**file name** |
_________________________________________
|                        | a.txt        | <<----Click a.txt    
_________________________________________
|                        | b.txt        |
_________________________________________

Best regards, Vivek

Answer №1

If you want to display content in a new popup.aspx page with the filename as a query parameter, you can follow this example below:

<asp:GridView ID="FilterGrid" runat="server" AutoGenerateColumns="False" >
    <Columns>
        <asp:TemplateField HeaderText="FileName" >
            <ItemTemplate>
               <asp:HyperLink ID="ActionHyperLink" runat="server" Text='<%# Eval("FileName") %>' NavigateUrl='<%# Eval("FileName","~/FilePopUp.aspx?filename={0}") %>' Target="_blank" />
               <asp:HyperLink ID="HyperLink2" runat="server" Text='<%# Eval("FileName") %>' NavigateUrl='<%# String.Format("filepopup.aspx?filename={0}", Eval("filename")) %>' onclick="javascript:w= window.open(this.href,'DownloadFile','left=20,top=20,width=500,height=500,toolbar=0,resizable=0');return false;"></asp:HyperLink>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

The Page_Load method for the popup page:

protected void Page_Load(object sender, EventArgs e)
{
            if (Request.QueryString["filename"] != null)
            {
                //Retrieve content from the database
                byte[] fileContent = ....;
                Response.Clear();
                string doctype = ...;
                if (doctype == ".doc")
                {
                    Response.ContentType = "application/msword";
                }
                else if (doctype == ".pdf")
                {
                    Response.ContentType = "application/pdf";
                }
                else if (doctype == ".xls")
                {
                    Response.ContentType = "application/vnd.ms-excel";
                }
                else if (doctype == ".xlsx")
                {
                    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                }
                Response.BinaryWrite(fileContent);
            }
}

Answer №2

Include a link button or regular button for revealing the filename. Add a div with runat="server" to reveal the file's content.

Manage the file name button click action. When clicked, retrieve and display the file content within the div using InnerHTML property.

The instructions above apply specifically to showcasing text/html data.

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

Tips for creating horizontal dividers with CSS in Vuetify using <v-divider> and <v-divider/> styling

Currently, I am working on a project using Vue.js and adding Vuetify. However, I need to use a component. .horizontal{ border-color: #F4F4F4 !important; border-width: 2px ; } <v-divider horizontal class=" horizontal ...

Utilizing Gmap4Rails.direction within a dynamically loaded partial using AJAX

I have a list that shows various places along with their distances from a given address. This list is regularly updated through ajax when the filtering system is utilized. Within my partial _place.html.haml, I include the following code snippet: - distanc ...

Is there a way to convert this asynchronous function into a synchronous one so that it returns the value immediately

When it comes to making a Nodejs/Javascript method synchronous, there are several solutions offered by the community. Some suggest using libraries like async and fibrous, but these involve wrapping functions externally. However, I am in search of a soluti ...

"Encountering a Problem with Assigning Variables in Vue

My issue revolves around the integration of VueJs, Vue-Resource, and Laravel. The problem occurs when attempting to assign a local variable to response data received from an AJAX request using vue-resource. Code Javascript <script> flags_ ...

When accessing the defaultValue property of a select element, it will result in

Here is a typical HTML dropdown menu: <select name="email" id="email"> <option value="2" selected="selected">Before redirecting to PayPal</option> <option value="1">After payment is successful</option> <opti ...

Transforming the JSON data into a text format

I have a JSON object structured like this: { "name": "ok", "country": "US", "phone": "900", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1f70745f727e767331707c">[email protected]</a>", ...

JavaScript - Display all comments

Here's the structure of my JSON data: { "comment_ds": [ { "c_user": [ "Alice", "Alice", "Alice", "Alice" ...

Ensuring model accuracy in Asp.Net Core prior to initiating an Ajax request via JavaScript

Here is a snippet of code that I am currently using, which is triggered on a button click event. The question I have is regarding the validation of my viewmodel object before sending an ajax call. I can see model errors in JavaScript, but I'm unsure o ...

Error encountered when accessing Spotify API. The requested action requires proper permissions which are currently missing. Issue arises when attempting to

I am attempting to use the spotify-web-api-node library to play a track on my application const playSong = async () => { // Verify access token with console.log(spotifyApi.getAccessToken()) setCurrentTrackId(track.track.id); setIsPlay ...

Incorporating a Streamlit Application into an Established React.js Project via an iFrame

I am in the process of incorporating a Streamlit app into my existing React.js application to take advantage of its data analysis and visualization features. Can this integration be accomplished using an iFrame? Has anyone successfully embedded a Streamlit ...

Do specific elements of typography adjust according to the size of the window?

I'm always amazed by the creative solutions that come out of this community. So I'm reaching out to see if anyone knows a way to achieve something unique with CSS! Specifically, I'm curious if it's possible to make certain horizontal p ...

Create a new function within the GraphQL Resolvers file

I am trying to define a function within the same ts file as where I specify the resolvers export const resolvers = { Query: { books: () => { return [ { title: 'Harry Potter and the Chambe ...

I'm having trouble setting up Stripe Elements in PHP. It seems like there's a communication issue between my PHP code and my JS

New to setting up Stripe Elements, I've followed the documentation closely. Installed the necessary JS modules, included the Stripe API, and connected it to the Stripe JS. In my index.php file, PHP script is at the top with HTML and JavaScript below i ...

Retrieving the ID from the element that was clicked

Here is a code snippet that allows for the changing of color and text when an href link is clicked. /* Function to change the color of the button upon click */ function changeColor(element) { alert(element.target.id); if (element.innerHTML == "Selec ...

``Take your website to the next level with a customized navigation menu

I'm currently in the process of developing a CMS for my website and I've reached the Navigation part. Can anyone provide me with tips or direct me to a tutorial on how to create a dynamic navigation menu? Thank you in advance. Below is a snippet ...

Merge floating and absolute positioning techniques

Creating a calendar exhibiting all events in one div requires precise positioning based on the values of top and height. Let me demonstrate this concept. In the image below, both 6am events are aligned vertically. This alignment issue can be resolved by u ...

Buttons in Datatables fail to appear when using ajax loading

I've been trying to solve this issue for a while now, but I just can't seem to figure it out. According to the documentation, adding initComplete should make the buttons appear, but I am still facing difficulties. Am I overlooking something? I&a ...

Is there a standardized code template or design pattern that can be applied for handling mouse clicks or button presses?

One common issue I frequently encounter with Winforms applications is the GUI thread becoming unresponsive while a lengthy task is running, or even ceasing to refresh altogether (I know, threading is needed). Is there a specific code template or design pa ...

Jenkins encountered an issue where script execution was blocked on <URL> due to the document's frame being sandboxed without the 'allow-scripts' permission set

When using an iFrame in HTML, it's always best to remember to sandbox it and set the 'allow-scripts' permission to true. However, I'm facing an issue in my pure Angular JS application where there is no iFrame present. It runs smoothly ...

Issue with rendering React Three JS in the browser

I recently attempted to follow a tutorial at https://www.youtube.com/watch?v=wRmeFtRkF-8 However, upon running my code, all I see is a blank canvas with a black background (as specified in the CSS). Interestingly, I can tell that the canvas is functional ...