I would like to display all my pictures in my folder "Images_uploads" folder into MVC View. So its display on the site. But nothing seems to work..
{
<form method="post" action="/Images_upload" enctype="multipart/form-data">
<input name="ImageUploaded" type="file">
<input type="submit">
</form>
<List<String> li = ViewData["~/images_upload"] as List<String>;
foreach (var picture in li)
<img src = '@Url.Content("~/images_upload" + picture)' alt="Hejsan" />
}
There is a very simple way to store images in database from MVC application. Step 1: First we create a class in model folder. Step 2: Create Action Method in Controller class . Step 6: Display an image form database on view.
Generally, the loops in asp.net mvc razor view will work same as other programming languages. We can define the loop inside or outside the code block in razor, and we can use the same foreach looping concept to assign value to define the condition.
ASP.NET MVC view can't have more than one model so if we need to display properties from more than one model in the view, it is not possible.
You should probably do this kind of thing in your controller. Use EnumerateFiles
to get a listing of all files in a folder:
// controller
public ActionResult MyAction()
{
...
ViewBag.Images = Directory.EnumerateFiles(Server.MapPath("~/images_upload"))
.Select(fn => "~/images_upload/" + Path.GetFileName(fn));
return View(...);
}
// view
@foreach(var image in (IEnumerable<string>)ViewBag.Images))
{
<img src="@Url.Content(image)" alt="Hejsan" />
}
Even better, use a strongly-typed view model, like this:
// model
class MyViewModel
{
public IEnumerable<string> Images { get; set; }
}
// controller
public ActionResult MyAction()
{
var model = new MyViewModel()
{
Images = Directory.EnumerateFiles(Server.MapPath("~/images_upload"))
.Select(fn => "~/images_upload/" + Path.GetFileName(fn))
};
return View(model);
}
// view
@foreach(var image in Model.Images)
{
<img src="@Url.Content(image)" alt="Hejsan" />
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With