Reputation: 51
Hi everyone I am trying to display all the images I have in a folder and I get this error nullreference exception Additional information: Object reference not set to an instance of an object." when it gets to Model.Images, i put a break point on the foreach line and the model is empty even though there is images in the folder, any idea how to fix this?
Thanks for any help with this issue.
controller
public ActionResult Getimages()
{
var model = new imagesModel()
{
Images = Directory.EnumerateFiles(Server.MapPath("~/Img"))
.Select(fn => "~/Img" + Path.GetFileName(fn))
};
return View(model);
}
model
public class imagesModel
{
public IEnumerable<string> Images { get; set; }
}
View
@model MyProject.Models.imagesModel
@foreach (var image in Model.Images)
{
<img src = "@Url.Content(image)" alt = "image" />
}
Upvotes: 0
Views: 1863
Reputation: 1356
You just forgot to insert /
in path.
Insert
Images = Directory.EnumerateFiles(Server.MapPath("~/Img"))
.Select(fn => "~/Img/" + Path.GetFileName(fn))
in place of
Images = Directory.EnumerateFiles(Server.MapPath("~/Img"))
.Select(fn => "~/Img" + Path.GetFileName(fn))
And I have Img
folder in here:
Upvotes: 0
Reputation: 9299
Are you referring the images from App_data folder. well, it will not work because HttpRequest doesn't goes inside the App_data folder. it's restricted folder.
Unable to access images stored inside my App_Data folder
Make sure your app_data does have some images. maybe its' have no images that's why it's not working.
Upvotes: 0
Reputation: 639
i think you need to ass ToLost();
So 1. return View(model).ToList();
Or 2.
Images = Directory.EnumerateFiles(Server.MapPath("~/App_Data"))
.Select(fn => "~/App_Data" +
Path.GetFileName(fn).ToList();
Upvotes: 0
Reputation: 4130
@model MyProject.Models.imagesModel
@foreach (var image in Model.Images)
{
<img src = "@Url.Content(image)" alt = "image" />
}
Upvotes: 1