I work in aspnet core mvc technology, I manage to add an image, it does go to wwwroot, but the image does not display well in the browser Example: enter image description here
My Controller:
[HttpPost,ActionName("CreateAnimal")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateAnimal([FromForm] CreateAnimalViewModel model)
{
string wwwPath = _Environment.WebRootPath;
string contentPath = _Environment.ContentRootPath;
ModelState.Clear();
model.Animal!.Category = _context.Categories.Where(c => c.CategoryId == model.Animal.CategoryId).FirstOrDefault()!;
var path = Path.Combine(wwwPath, "Images", model.Photo!.FileName);
if (model.Photo.Length > 0)
{
using var stream = new FileStream(path, FileMode.Create);
await model.Photo.CopyToAsync(stream);
}
model.Animal.PhotoUrl = path;
_context.Add(model.Animal);
if (TryValidateModel(model))
{
_context.Add(model.Animal!);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Manager));
}
ViewBag.CategoryId = new SelectList(_context.Categories, "CategoryId", "Name");
return View();
}
My View:
@model IEnumerable<PetShop.Data.Models.Animal>
<table id="Table">
<thead>
<tr>
<th>@Html.DisplayNameFor(model => model.PhotoUrl)</th>
<th>@Html.DisplayNameFor(model => model.Name)</th>
<th>@Html.DisplayNameFor(model => model.BirthDate)</th>
<th>@Html.DisplayNameFor(model => model.Description)</th>
<th>@Html.DisplayNameFor(model => model.Category.Name)</th>
<th>@Html.DisplayNameFor(model => model.Category)</th>
<th>Edit Animel</th>
<th>Delete Animel</th>
@foreach (var item in Model!) {
<img class="Images" src="~/Images/@Html.DisplayFor(modelItem => item.PhotoUrl)">
</td>
<td>@Html.DisplayFor(modelItem => item.Name)</td>
<td>@Html.DisplayFor(modelItem => item.BirthDate)</td>
<td>@Html.DisplayFor(modelItem => item.Description)</td>
<td>@Html.DisplayFor(modelItem => item.Category.Name)</td>
<td>@Html.DisplayFor(modelItem => item.CategoryId)</td>
<a asp-action="EditAnimel" asp-route-id="@item.AnimalId">
<input type="submit" value="Edit">
</a>
<a asp-action="DeleteAnimel" asp-route-id="@item.AnimalId">
<input type="submit" value="Delete">
</a>
}
Below is a work demo, you can refer to it.
ProductController.cs:
Index.cshtml:
Success.cshtml:
Product