Reputation: 8964
I have images included with my ASP.NET project under the img
folder. I'm trying to automate the process of displaying the images without having to manually add each one.
I tried:
@foreach (var image in Directory.GetFiles(Server.MapPath("/img/portfolio/engagement")))
{
<li class="span3"><a href="#" class="thumbnail"><img src="@image"/></a></li>
}
This outputs:
<ul class="thumbnails">
<li class="span3"><a href="#" class="thumbnail"><img src="C:\Users\Cody\Documents\CMBS\CodySolution\CodySolution\img\portfolio\engagement\IMG_0093.jpg"/></a></li>
<li class="span3"><a href="#" class="thumbnail"><img src="C:\Users\Cody\Documents\CMBS\CodySolution\CodySolution\img\portfolio\engagement\IMG_0130.jpg"/></a></li>
<li class="span3"><a href="#" class="thumbnail"><img src="C:\Users\Cody\Documents\CMBS\CodySolution\CodySolution\img\portfolio\engagement\IMG_0144.jpg"/></a></li>
<li class="span3"><a href="#" class="thumbnail"><img src="C:\Users\Cody\Documents\CMBS\CodySolution\CodySolution\img\portfolio\engagement\IMG_9931.jpg"/></a></li>
</ul>
This doesn't work. The images do not show and when I try to follow the direct link, it tells me A potentially dangerous Request.Path value was detected from the client (:).
What is the proper way to do what I'm trying to do?
Upvotes: 1
Views: 934
Reputation: 4568
This happens because Server.MapPath
gives you the physical directory of where your web app resides on your server.
Try using Url.Content()
instead. This will give you an http path like http://www.yoursite.com/Content/file.jpg
For example:
var path = "~/Content/Whatever/";
var listOfFileNames = Directory.GetFiles(Server.MapPath(path))
.Select(p => path + Path.GetFileName(p));
@foreach (var item in listOfFileNames)
{
<img src="@Url.Content(item)" />
}
Upvotes: 2