I'm creating an Animal Shelter application and when someone looks at the animals, I have it displayed using bootstrap cards. I don't know how to get the images to display though. I'm very new to MVC and C# so I don't understand a lot of the answers that are posted online for this particular question.
Model:
public class Pet
{
public int Pet_ID { get; set; }
// Other properties
public string Photo { get; set; }
}
Controller:
public ActionResult ShowCats()
{
var cats = db.Pets.Where(c => c.Species_Type == Species_Type.Cat).ToList();
return View(cats);
}
View:
<div class="container">
@foreach (var item in Model)
{
<div class="card col-md-3">
<img class="center-block" src="@Html.DisplayFor(modelItem => item.Photo)" height="300" width="230" alt=@Html.DisplayFor(modelItem => item.Name) />
// other display tags
</div>
}
Create() - This is how I get the image from upload
[HttpPost]
public ActionResult Create(Pet upload, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var guid = Guid.NewGuid().ToString();
var path = Path.Combine(Server.MapPath("~/Uploads"), guid + fileName);
file.SaveAs(path);
string fl = path.Substring(path.LastIndexOf("\\"));
string[] split = fl.Split('\\');
string newpath = split[1];
string imagepath = "~/Uploads/" + newpath;
upload.Photo = imagepath;
db.Pets.Add(upload);
db.SaveChanges();
}
TempData["Success"] = "Upload successful";
return RedirectToAction("Index");
}
return View();
}
I tried this method, but it interfered with my Create() because it couldn't convert string to byte (I changed my model from string Photo to byte[] Photo to try this particular way).
public ActionResult GetImage( int id )
{
var photo = (new ApplicationDbContext()).Pets.Find(id).Photo;
return File( imageData, "image/jpg" );
}
this was the View for it:
<img class="center-block" src="@Url.Action("GetImage", "Pet", new { id = item.Pet_ID })" height="300" width="230" alt=@Html.DisplayFor(modelItem => item.Name) />