I am trying to a single image upload. but the problem is when I upload an image, I find null (i debugged). Here is my code:
[HttpPost]
public async Task <IActionResult> Create(Image products, IFormFile image)
{
if (ModelState.IsValid)
{
if (image != null)
{
var name1 = Path.Combine(_he.WebRootPath + "/Images", Path.GetFileName(image.FileName));
var stream2 = new FileStream(name1, FileMode.Create);
await image.CopyToAsync(stream2);
products.ImageC = "Images/" + image.FileName;
}
if (image == null)
{
products.ImageC = "Images/NoImageFound.jpg";
}
_db.Images.Add(products);
_db.SaveChanges();
return RedirectToAction(nameof(Index));
}
return View(products);
}
_Create.cshtml
<form asp-action="Create" method="post" enctype="multipart/form-data">
<div class="p-4 rounded border">
<div asp-validation-summary="ModelOnly" class="text-danger">
</div>
<div class="form-group row">
<div class="col-5">
<p class="text-bold mb-2">Image</p>
<input asp-for="ImageC" class="" type="file" />
</div>
</div>
<div class="form-group">
<input type="submit" class="btn btn-danger form-control" value="Submit" />
</div>
</div>
</form>
//Image.cs (Model)
public class Image
{
public int Id { get; set; }
public string ImageC { get; set; }
}
When I type the submit button then:-
then I debugged my code and found this issue:-
I don't understand why I found this null reference? how I will upload my image? I am still a beginner, please help.