I have a question concerning the correctness of the reading and displaying the image in ASP.NET Core MVC web application.
This is the way I am reading image names from a specific folder (I am using IHostingEnvironment _hostingEnvironment
to get the rootPath
):
public class GetRandomImageForGalleryView : IGetRandomImageFromFolder
{
private string rootPath;
public GetRandomImageForGalleryView(string rootPath)
{
this.rootPath = rootPath;
}
public string[] getImage()
{
return ReadPhotosFromDirectory();
}
private string[] ReadPhotosFromDirectory()
{
string[] fileLocations = Directory.GetFiles(rootPath+"\\lib\\Images\\Nature").Select(path => Path.GetFileName(path))
.ToArray();
return fileLocations;
}
}
And this is the way I am displaying them:
@model IGetRandomImageFromFolder
@{
ViewBag.Title = "Gallery";
}
<div class="container">
<div class="row">
@{
foreach (var item in Model.getImage())
{
<img src="~/lib/Images/Nature/@item" style="max-width: 500px;">
}
}
</div>
</div>
Basically I just replace the image name.
Is this a good way? If not, why? Any other remarks would be helpful as well.
-
\$\begingroup\$ I would simplify the GetImage() method as suggested by @svick and I would also avoid the method call from the Razor view, build the list of files in a controller and then pass it to the view rather. \$\endgroup\$Stefano d'Antonio– Stefano d'Antonio2016年07月02日 17:26:48 +00:00Commented Jul 2, 2016 at 17:26
1 Answer 1
You could simplify your getImage()
method pretty significantly to just:
public IEnumerable<string> GetImage() =>
Directory.GetFiles(rootPath + @"\lib\Images\Nature").Select(Path.GetFileName);
Things I changed:
- Changed capitalization to follow .Net naming guidelines.
- Removed unnecessary method
ReadPhotosFromDirectory()
. - Removed unnecessary variable
fileLocations
. - Used verbatim string to avoid having to escape backslashes.
- Used method group to delegate conversion instead of lambda.
- Got rid of
ToArray()
, which didn't serve any purpose, and changed return type toIEnumerable<string>
. - Used C# 6.0 expression bodied method.
-
\$\begingroup\$ Wow, that did not answer my question if it is a good way to display this way by passing in the image like that in the razor view, however you gave me a nice lesson to research. Yeah I am coming from Java background so naming is something I still will have to look around in .Net as well bunch of things I will look now differently at, big thanks :)) \$\endgroup\$vsarunov– vsarunov2016年07月02日 17:52:14 +00:00Commented Jul 2, 2016 at 17:52
-
\$\begingroup\$ @vsarunov there is nothing wrong in using razor to display your images this way \$\endgroup\$Tolani– Tolani2016年07月03日 01:11:11 +00:00Commented Jul 3, 2016 at 1:11