R S
R S

Reputation: 27

How to show FIleName and download link for file using ASP.Net MVC?

I am having trouble in rendering the files listed in the Folder. I am able to display the URL for the files listed in folder, but instead of Link I want it to show FileName and not the URL. Also, I am looking to be able to add a hyperlink to respective files so that can be downloaded from the Folder.

Model Class

public string AgentName { get; set; }

public string DealType { get; set; }

public HttpPostedFileBase[] files { get; set; } //Used to upload multiple files or images

Action Method to call

public ActionResult DealInfo(int id)
{
using(Db db = new Db())
{

ManagementDeal deal = db.ManagementDeals.FirstOrDefault(x => x.DealId == id);

var dId = deal.DealId;

ViewBag.DealID = dId;


string[] filePaths = Directory.GetFiles(Server.MapPath("~/Images/Uploads/Deals/" + id));
                
                
ViewBag.FilePath = filePaths;

View to render the Files from Folder

<div class="container-fluid">
    <div class="row">
        @foreach (string item in ViewBag.FilePath)
        {
            <div class="col-sm-2">
                <div class="text-center">
                    <h1><i class="fas fa-file-alt text-warning"></i></h1>
                    <a href="~/Images/Uploads/Deals/@item" target="_blank">@item</a><br />
                </div>
            </div>
        }
    </div>
</div>

So,

  1. Show file name instead of the URL
  2. should be able to download file on clicking Name of File.

Screen shot is here for my current View https://prnt.sc/1343b8d

Thank you in advance.

Upvotes: 0

Views: 891

Answers (1)

R S
R S

Reputation: 27

Managed to fix it with the below code in Controller Action

ViewBag.FilePath = Directory.EnumerateFiles(Server.MapPath("~/Images/Uploads/Deals/" + id ))
                                                .Select(fn => Path.GetFileName(fn));

Using above render ViewBag in a View using foreach and can show the file name and download the file on click

Upvotes: 1

Related Questions