Retrieve & Display all image files from wwwroot folder in asp.net core razor pages

/ / 1 Comments

Get all images in asp.net core: Here in this article, we are going to learn a simple but useful method, to display all the images from the wwwroot folder of our asp.net core web app. 

As we know in asp.net core by default all the static files, such as HTML, CSS, images, and JavaScript have been stored within the project's web root director i.e wwwroot folder. 

We can also change the default directory by using the UseWebRoot method, for detail you can check how to change the default wwwroot directory.

Well in this article first we get all the list of images from wwwroot/uploadfiles/images folder and then display it on page load using razor pages.

So am breaking this into 2 parts as shown below.

  1. Retrieve the list of all the images in a directory ( in our case it is wwwroot/uploadfiles/images)
  2. Display/show all image files from the wwwroot directory on page load.

At the time of writing the code am using a version of asp.net core 3.1

Let's first create a new project, here I am selecting razor pages.

This is how our project solution file structure looks like.

Project solution file structure


Now let's head towards the coding part by open index.cshtml page which is our default page. Now we create and initialize IWebHostEnvironment inside IndexModel constructor as written in the below code.

private readonly IWebHostEnvironment webHostEnvironment;

public IndexModel(IWebHostEnvironment webHostEnvironment)
{	
    this.webHostEnvironment = webHostEnvironment;
} 

We must also import namespace Microsoft.AspNetCore.Hosting;

 using Microsoft.AspNetCore.Hosting;

In razor pages, by default OnGet method gets called whenever the page gets load. And OnPost methods gets called whenever a post request is made. Here we use the OnGet method as we want to display all images on page load.

#1: Retrieve the list of all the images from wwwroot folder.

By adding the below code OnGet method, we retrieve a list of all the image details which are present in the wwwroot/uploadfiles/images folder.

 public IActionResult OnGet()
{
	var provider = new PhysicalFileProvider(webHostEnvironment.WebRootPath);
	var contents = provider.GetDirectoryContents(Path.Combine("uploadedfiles", "images"));
	var objFiles = contents.OrderBy(m => m.LastModified);
   
	return new JsonResult(objFiles);
}

Output:

 #2: Display all image files from a wwwroot directory on page load.

Here we want to display images on page-load. So OnGet method instead of returning JsonResult, will return Page() and bind values to variable ImageList. Below written code set all file details in variable ImageList, which we use later at page design.

 [BindProperty]
public List<string> ImageList { get; set; }

public IActionResult OnGet()
{
	var provider = new PhysicalFileProvider(webHostEnvironment.WebRootPath);
	var contents = provider.GetDirectoryContents(Path.Combine("uploadedfiles", "images"));
	var objFiles = contents.OrderBy(m => m.LastModified);

	ImageList = new List<string>();
	foreach (var item in objFiles.ToList())
	{
		ImageList.Add(item.Name);
	}
	 return Page();
   // return new JsonResult(objFiles);
}   

Now we have all the image details next, we want to display images. For that, we need to add an image tag on the page design and set it image src value from our Model.ImageList.

To make the page design look nice we have added some CSS classes on the image tag .i.e ( float-left, p-2). Also if you want to remove any existing style then in jQuery remove style is very simple. The final code looks like as written below:

 <div class="row">
    <div class="col container">
        <div class="col-10">
            @foreach (var items in Model.ImageList)
            {
                var iPhotoUrl = "/uploadedfiles/images/" + items;
                <img class="float-left p-2" src="@iPhotoUrl" height="150" />

            }
        </div>
    </div>
</div>

Output:

Other Reference:

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

1 Comments