Haree
Haree

Reputation: 53

How to display any one of the images or first image from the folder in mvc application

How to display any one of the image or first image from the folder in my asp.net mvc application

now i am using like this

<img src="~/UserProfileImages/Images/100.jpg" class="img-responsive" alt="" />

but i want to display first image from folder without file name or extension... I have many images in folder.

Upvotes: 1

Views: 587

Answers (1)

GregH
GregH

Reputation: 5459

    public class SomeController
    {
        public ActionResult Index()
        {
            var myModel = new ImageModel();
            var imagePaths = ReadPhotosFromDirectory();

            if(!imagePaths.IsNullOrEmpty())
            {
                //get the first file path from the directory
                myModel.ImageSrc = imagePaths[0];
            }

            return View(myModel);
        }

        //this method assumes all files in the directory are images.
        //you should check the file extensions as well to be safer
        private string[] ReadPhotosFromDirectory()
        {

            string[] fileLocations = Directory.GetFiles("\\your\\folder\\path").ToArray();
            return fileLocations;
        }
    }

then in your view reference the image source (view is Index.cshtml in this example):

@model MyApp.ImageModel

<img src="@Model.ImageSrc" class="img-responsive" alt="" />

Upvotes: 1

Related Questions