Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get returned null.
I'm stuck, guys, Please help me! When I'm trying to add some products on my database there is an exception. There is my controller code:
public class ProductController : Controller
{
private readonly ApplicationDbContext _db;
private readonly IWebHostEnvironment _webHostEnvironment;
public ProductController(ApplicationDbContext db, IWebHostEnvironment webHostEnvironment)
{
_db = db;
_webHostEnvironment = webHostEnvironment;
}
public IActionResult Index()
{
IEnumerable<Product> objList = _db.Product;
foreach (var obj in objList)
{
obj.Category = _db.Category.FirstOrDefault(u => u.Id == obj.CategoryId);
}
return View(objList);
}
/// <summary>
/// GET method for CREATE
/// </summary>
/// <returns></returns>
public IActionResult Upsert(int? id)
{
ProductVM productVM = new ProductVM()
{
Product = new Product(),
CategorySelectList = _db.Category.Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
})
};
if (id == null)
{
return View(productVM); //creating
}
else
{
productVM.Product = _db.Product.Find(id);
if (productVM.Product == null)
{
return NotFound();
}
return View(productVM);
}
}
/// <summary>
/// POST method for CREATE
/// </summary>
/// <returns></returns>
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upsert(ProductVM productVM)
{
if (ModelState.IsValid)
{
var files = HttpContext.Request.Form.Files;
string webRootPath = _webHostEnvironment.WebRootPath;
if (productVM.Product.Id == 0)
{
string upload = webRootPath + WC.ImagePath;
string fileName = Guid.NewGuid().ToString();
string extention = Path.GetExtension(files[0].FileName);
using (var fileStream = new FileStream(Path.Combine(upload, fileName + extention), FileMode.Create))
{
files[0].CopyTo(fileStream);
}
productVM.Product.Image = fileName + extention;
_db.Product.Add(productVM.Product);
}
else
{
//updating
}
_db.SaveChanges();
return RedirectToAction("Index");
}
return View();
}
}
There is code from View fro Upsert
@{
var title = "Создать продукт";
}
<form method ="post" enctype="multipart/form-data">
* @if (Model.Product.Id!=0)* //ERROR PLACE
{
title = "Edit";
<input asp-for="Product.Id" hidden />
}
<div class= "border p-3">
<div class="form-group row">
<h2 class="text-info pb-4">@title</h2>
</div>
<div class="row">
<div class="col-8">
<div class="form-group row">
<div class="col-4 pb-4">
<label asp-for="Product.Name"></label>
</div>
<div class="col-8">
<input asp-for="Product.Name" class="form-control" />
<span asp-validation-for="Product.Name" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-4 pb-4">
<label asp-for="Product.Price"></label>
</div>
<div class="col-8">
<input asp-for="Product.Price" class="form-control" />
<span asp-validation-for="Product.Price" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-4 pb-4">
<label asp-for="Product.Description"></label>
</div>
<div class="col-8">
<textarea asp-for="Product.Description" class="form-control summernote"></textarea>
</div>
</div>
<div class="form-group row">
<div class="col-4 pb-4">
<label asp-for="Product.Image"></label>
</div>
<div class="col-8">
<input type="file" name="files" id="uploadBox" multiple class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-4 pb-4">
<label asp-for="Product.CategoryId"></label>
</div>
<div class="col-8">
<select asp-for="Product.CategoryId" asp-items="@Model.CategorySelectList" class="form-control">
<option disabled>--Choose category-- </option>
</select>
<span asp-validation-for="Product.CategoryId" class="text-danger"></span>
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-4 row p-3">
<div class="col">
@if (Model.Product.Id != 0)
{ //update
<input type="submit" class="btn btn-info w-100" value="Update"/>
}
else
{ //create
<input type="submit" onclick="return validateInput()" class="btn btn-info w-100" value="Create"/>
}
</div>
<div class="col">
<a asp-action = "Index" class="btn btn-success w-100"> Back </a>
</div>
</div>
</div>
</div>
<div class="col-4">
@* Keep this empty *@
</div>
</div>
</div>
</form>
@section Scripts
{
@{ <partial name = "_ValidationScriptsPartial" />}
<script>
$(document).ready(function() {
$('.summernote').summernote({height:250});
});
function validateInput() {
if (document.getElementById("uploadBox").value == "") {
Swal.fire(
'Error!',
'Please, upload the image!',
'error')
return false;
}
else return true;
}
</script>
}
Product Model:
public class Product
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Description { get; set; }
[Required]
[Range(1, int.MaxValue]
public double Price { get; set; }
public string Image { get; set; }
public int CategoryId { get; set; }
[ForeignKey("CategoryId")]
public virtual Category Category { get; set; }
}
ProductVM Model
public class ProductVM
{
public Product Product { get; set; }
public IEnumerable<SelectListItem> CategorySelectList { get; set; }
}
It's my fist time working with ASP.net and I've tried to follow the steps from the course, but I can't find an error for two days straight, so I hope someone can help me.