I need just to display the multiple images I insert it save will in path, but when he showed it does show up. I don't know where is my problem but this is my code please guys help me?
My Controller
public async Task<ActionResult> Create(Inbox model, IEnumerable<HttpPostedFileBase> files)
{
var currentUser = await manager.FindByIdAsync(User.Identity.GetUserId());
if (ModelState.IsValid)
{
model.User = currentUser;
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/FilesAPP"), fileName);
file.SaveAs(path);
path = Url.Content(Path.Combine("~/FilesAPP", fileName));
}
}
db.Inboxs.Add(model);
db.SaveChanges();
string url = Url.Action("List");
return Json(new { success = true, url = url });
}
return View(model);
}
My model
public string Files { get; set; }
And my View
<img width="200" height="150" src="@Url.Content(Model.Files))" />
How can I display my images guys?
first create a list for Files
public async Task<ActionResult> Create(Inbox model, IEnumerable<HttpPostedFileBase> files)
{
List<Inbox>lst=new List<Inbox>();
var currentUser = await manager.FindByIdAsync(User.Identity.GetUserId());
if (ModelState.IsValid)
{
model.User = currentUser;
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/FilesAPP"), fileName);
file.SaveAs(path);
path = Url.Content(Path.Combine("~/FilesAPP", fileName));
lst.add(new Inbox{Files=path});
//you files added here
}
}
db.Inboxs.Add(model);
db.SaveChanges();
string url = Url.Action("List");
return Json(new { success = true, url = url });
}
return View(model);
}
after in your view
@model List<Inbox>
@foreach (var item in Model.Files)
{
<img src="@item.FilePath" />
}
I see you are saving your files in the controller in a loop but you are not updating your model with files paths. Update your model with file paths in controller and pass the model to the view like you are doing. Then, in your view you must also do a loop, iterate over the images and for each one render an img tag with the source as the file path saved in controller.
Assuming you are using Razor ASP.NET syntax, just do something like this in your view as you done in controller. but make sure to attach the files to your model first:
@foreach (var item in Model.Files)
{
<img src="@item.FilePath" />
}
Here is another post with example of loops in Razor, good luck!
MVC Razor @foreach