**System.NullReferenceException: ‘Object reference not set to an instance of an object
Microsoft.AspNetCore.Mvc.Razor.RazorPage.Model.get returned null **
Here is my code
Update.cshtml
<code>@model WebBanHang.Models.Product
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<form asp-action="Update" method="post" enctype="multipart/form-data">
<h2>Update Product</h2>
<hr />
<input asp-for="Id" type="hidden" />
<div class="row">
<div class="col-md-4">
@if (!string.IsNullOrEmpty(Model.ImageUrl))
{
<img src="/@Model.ImageUrl" style="width:300px" id="previewImage" />
}
else
{
<span>No image available</span>
}
</div>
<div class="col-md-8">
<div class="form-group pb-2">
<label>Name</label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group pb-2">
<label>Discription</label>
<textarea asp-for="Description" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group pb-2">
<label>Price</label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="form-group pb-2">
<label>Category</label>
<select asp-for="CategoryId" asp-items="@ViewBag.CategoryList" class="form-control">
<option disabled selected>==Select category===</option>
</select>
<span asp-validation-for="CategoryId" class="text-danger"></span>
</div>
@* <img src="/@Model.ImageUrl" style="width:300px" id="previewImage" /> *@
<div class="form-group pb-2">
<label>Product Image</label>
<input asp-for="ImageUrl" type="file" class="form-control" />
</div>
<button type="submit" class="btn btn-primary"> Update </button>
<a asp-action="Index" class="btn btn-secondary">Back to List</a>
</div>
</div>
</form>
@section Scripts {
<script>
document.querySelectorAll('input[type="file"]').forEach(input => {
input.addEventListener('change', function (event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function (e) {
const img = document.getElementById("previewImage");
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
});
</script>
}
</code>
<code>@model WebBanHang.Models.Product
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<form asp-action="Update" method="post" enctype="multipart/form-data">
<h2>Update Product</h2>
<hr />
<input asp-for="Id" type="hidden" />
<div class="row">
<div class="col-md-4">
@if (!string.IsNullOrEmpty(Model.ImageUrl))
{
<img src="/@Model.ImageUrl" style="width:300px" id="previewImage" />
}
else
{
<span>No image available</span>
}
</div>
<div class="col-md-8">
<div class="form-group pb-2">
<label>Name</label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group pb-2">
<label>Discription</label>
<textarea asp-for="Description" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group pb-2">
<label>Price</label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="form-group pb-2">
<label>Category</label>
<select asp-for="CategoryId" asp-items="@ViewBag.CategoryList" class="form-control">
<option disabled selected>==Select category===</option>
</select>
<span asp-validation-for="CategoryId" class="text-danger"></span>
</div>
@* <img src="/@Model.ImageUrl" style="width:300px" id="previewImage" /> *@
<div class="form-group pb-2">
<label>Product Image</label>
<input asp-for="ImageUrl" type="file" class="form-control" />
</div>
<button type="submit" class="btn btn-primary"> Update </button>
<a asp-action="Index" class="btn btn-secondary">Back to List</a>
</div>
</div>
</form>
@section Scripts {
<script>
document.querySelectorAll('input[type="file"]').forEach(input => {
input.addEventListener('change', function (event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function (e) {
const img = document.getElementById("previewImage");
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
});
</script>
}
</code>
@model WebBanHang.Models.Product
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<form asp-action="Update" method="post" enctype="multipart/form-data">
<h2>Update Product</h2>
<hr />
<input asp-for="Id" type="hidden" />
<div class="row">
<div class="col-md-4">
@if (!string.IsNullOrEmpty(Model.ImageUrl))
{
<img src="/@Model.ImageUrl" style="width:300px" id="previewImage" />
}
else
{
<span>No image available</span>
}
</div>
<div class="col-md-8">
<div class="form-group pb-2">
<label>Name</label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group pb-2">
<label>Discription</label>
<textarea asp-for="Description" class="form-control"></textarea>
<span asp-validation-for="Description" class="text-danger"></span>
</div>
<div class="form-group pb-2">
<label>Price</label>
<input asp-for="Price" class="form-control" />
<span asp-validation-for="Price" class="text-danger"></span>
</div>
<div class="form-group pb-2">
<label>Category</label>
<select asp-for="CategoryId" asp-items="@ViewBag.CategoryList" class="form-control">
<option disabled selected>==Select category===</option>
</select>
<span asp-validation-for="CategoryId" class="text-danger"></span>
</div>
@* <img src="/@Model.ImageUrl" style="width:300px" id="previewImage" /> *@
<div class="form-group pb-2">
<label>Product Image</label>
<input asp-for="ImageUrl" type="file" class="form-control" />
</div>
<button type="submit" class="btn btn-primary"> Update </button>
<a asp-action="Index" class="btn btn-secondary">Back to List</a>
</div>
</div>
</form>
@section Scripts {
<script>
document.querySelectorAll('input[type="file"]').forEach(input => {
input.addEventListener('change', function (event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function (e) {
const img = document.getElementById("previewImage");
img.src = e.target.result;
};
reader.readAsDataURL(file);
}
});
});
</script>
}
ProductController.cs
<code>using WebBanHang.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace ProjectName.Controllers
{
public class ProductController : Controller
{
private readonly ApplicationDbContext _db;
private readonly Microsoft.AspNetCore.Hosting.IHostingEnvironment _hosting;
public ProductController(ApplicationDbContext db, Microsoft.AspNetCore.Hosting.IHostingEnvironment hosting)
{
_db = db;
_hosting = hosting;
}
//Hiển thị danh sách sản phẩm
public IActionResult Index()
{
var productList = _db.Products.Include(x => x.Category).ToList();
return View(productList);
}
//Hiển thị form thêm sản phẩm mới
public IActionResult Add()
{
//truyền danh sách thể loại cho View để sinh ra điều khiển DropDownList
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View();
}
//Xử lý thêm sản phẩm
[HttpPost]
public IActionResult Add(Product product, IFormFile ImageUrl)
{
if (ModelState.IsValid) //kiem tra hop le
{
if (ImageUrl != null)
{
//xu ly upload và lưu ảnh đại diện
product.ImageUrl = SaveImage(ImageUrl);
}
//thêm product vào table Product
_db.Products.Add(product);
_db.SaveChanges();
TempData["success"] = "Product inserted success";
return RedirectToAction("Index");
}
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View();
}
//Hiển thị form cập nhật sản phẩm
public IActionResult Update(int id)
{
var product = _db.Products.Find(id);
if (product == null)
{
return NotFound();
}
//truyền danh sách thể loại cho View để sinh ra điều khiển DropDownList
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View(product);
}
//Xử lý cập nhật sản phẩm
[HttpPost]
public IActionResult Update(Product product, IFormFile ImageUrl)
{
if (ModelState.IsValid) //kiem tra hop le
{
var existingProduct = _db.Products.Find(product.Id);
if (ImageUrl != null)
{
//xu ly upload và lưu ảnh đại diện mới
product.ImageUrl = SaveImage(ImageUrl);
//xóa ảnh cũ (nếu có)
if (!string.IsNullOrEmpty(existingProduct.ImageUrl))
{
var oldFilePath = Path.Combine(_hosting.WebRootPath,
existingProduct.ImageUrl);
if (System.IO.File.Exists(oldFilePath))
{
System.IO.File.Delete(oldFilePath);
}
}
}
else
{
product.ImageUrl = existingProduct.ImageUrl;
}
//cập nhật product vào table Product
existingProduct.Name = product.Name;
existingProduct.Description = product.Description;
existingProduct.Price = product.Price;
existingProduct.CategoryId = product.CategoryId;
existingProduct.ImageUrl = product.ImageUrl;
_db.SaveChanges();
TempData["success"] = "Product updated success";
return RedirectToAction("Index");
}
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View();
}
private string SaveImage(IFormFile image)
{
//đặt lại tên file cần lưu
var filename = Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
//lay duong dan luu tru wwwroot tren server
var path = Path.Combine(_hosting.WebRootPath, @"images/products");
var saveFile = Path.Combine(path, filename);
using (var filestream = new FileStream(saveFile, FileMode.Create))
{
image.CopyTo(filestream);
}
return @"images/products/" + filename;
}
//Hiển thị form xác nhận xóa sản phẩm
public IActionResult Delete(int id)
{
var product = _db.Products.Find(id);
if (product == null)
{
return NotFound();
}
return View(product);
}
//Xử lý xóa sản phẩm
[HttpPost, ActionName("Delete")]
public IActionResult DeleteConfirmed(int id)
{
var product = _db.Products.Find(id);
if (product == null)
{
return NotFound();
}
// xoá hình cũ của sản phẩm
if (!String.IsNullOrEmpty(product.ImageUrl))
{
var oldFilePath = Path.Combine(_hosting.WebRootPath, product.ImageUrl);
if (System.IO.File.Exists(oldFilePath))
{
System.IO.File.Delete(oldFilePath);
}
}
// xoa san pham khoi CSDL
_db.Products.Remove(product);
_db.SaveChanges();
TempData["success"] = "Product deleted success";
//chuyen den action index
return RedirectToAction("Index");
}
}
}
</code>
<code>using WebBanHang.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace ProjectName.Controllers
{
public class ProductController : Controller
{
private readonly ApplicationDbContext _db;
private readonly Microsoft.AspNetCore.Hosting.IHostingEnvironment _hosting;
public ProductController(ApplicationDbContext db, Microsoft.AspNetCore.Hosting.IHostingEnvironment hosting)
{
_db = db;
_hosting = hosting;
}
//Hiển thị danh sách sản phẩm
public IActionResult Index()
{
var productList = _db.Products.Include(x => x.Category).ToList();
return View(productList);
}
//Hiển thị form thêm sản phẩm mới
public IActionResult Add()
{
//truyền danh sách thể loại cho View để sinh ra điều khiển DropDownList
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View();
}
//Xử lý thêm sản phẩm
[HttpPost]
public IActionResult Add(Product product, IFormFile ImageUrl)
{
if (ModelState.IsValid) //kiem tra hop le
{
if (ImageUrl != null)
{
//xu ly upload và lưu ảnh đại diện
product.ImageUrl = SaveImage(ImageUrl);
}
//thêm product vào table Product
_db.Products.Add(product);
_db.SaveChanges();
TempData["success"] = "Product inserted success";
return RedirectToAction("Index");
}
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View();
}
//Hiển thị form cập nhật sản phẩm
public IActionResult Update(int id)
{
var product = _db.Products.Find(id);
if (product == null)
{
return NotFound();
}
//truyền danh sách thể loại cho View để sinh ra điều khiển DropDownList
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View(product);
}
//Xử lý cập nhật sản phẩm
[HttpPost]
public IActionResult Update(Product product, IFormFile ImageUrl)
{
if (ModelState.IsValid) //kiem tra hop le
{
var existingProduct = _db.Products.Find(product.Id);
if (ImageUrl != null)
{
//xu ly upload và lưu ảnh đại diện mới
product.ImageUrl = SaveImage(ImageUrl);
//xóa ảnh cũ (nếu có)
if (!string.IsNullOrEmpty(existingProduct.ImageUrl))
{
var oldFilePath = Path.Combine(_hosting.WebRootPath,
existingProduct.ImageUrl);
if (System.IO.File.Exists(oldFilePath))
{
System.IO.File.Delete(oldFilePath);
}
}
}
else
{
product.ImageUrl = existingProduct.ImageUrl;
}
//cập nhật product vào table Product
existingProduct.Name = product.Name;
existingProduct.Description = product.Description;
existingProduct.Price = product.Price;
existingProduct.CategoryId = product.CategoryId;
existingProduct.ImageUrl = product.ImageUrl;
_db.SaveChanges();
TempData["success"] = "Product updated success";
return RedirectToAction("Index");
}
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View();
}
private string SaveImage(IFormFile image)
{
//đặt lại tên file cần lưu
var filename = Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
//lay duong dan luu tru wwwroot tren server
var path = Path.Combine(_hosting.WebRootPath, @"images/products");
var saveFile = Path.Combine(path, filename);
using (var filestream = new FileStream(saveFile, FileMode.Create))
{
image.CopyTo(filestream);
}
return @"images/products/" + filename;
}
//Hiển thị form xác nhận xóa sản phẩm
public IActionResult Delete(int id)
{
var product = _db.Products.Find(id);
if (product == null)
{
return NotFound();
}
return View(product);
}
//Xử lý xóa sản phẩm
[HttpPost, ActionName("Delete")]
public IActionResult DeleteConfirmed(int id)
{
var product = _db.Products.Find(id);
if (product == null)
{
return NotFound();
}
// xoá hình cũ của sản phẩm
if (!String.IsNullOrEmpty(product.ImageUrl))
{
var oldFilePath = Path.Combine(_hosting.WebRootPath, product.ImageUrl);
if (System.IO.File.Exists(oldFilePath))
{
System.IO.File.Delete(oldFilePath);
}
}
// xoa san pham khoi CSDL
_db.Products.Remove(product);
_db.SaveChanges();
TempData["success"] = "Product deleted success";
//chuyen den action index
return RedirectToAction("Index");
}
}
}
</code>
using WebBanHang.Models;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace ProjectName.Controllers
{
public class ProductController : Controller
{
private readonly ApplicationDbContext _db;
private readonly Microsoft.AspNetCore.Hosting.IHostingEnvironment _hosting;
public ProductController(ApplicationDbContext db, Microsoft.AspNetCore.Hosting.IHostingEnvironment hosting)
{
_db = db;
_hosting = hosting;
}
//Hiển thị danh sách sản phẩm
public IActionResult Index()
{
var productList = _db.Products.Include(x => x.Category).ToList();
return View(productList);
}
//Hiển thị form thêm sản phẩm mới
public IActionResult Add()
{
//truyền danh sách thể loại cho View để sinh ra điều khiển DropDownList
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View();
}
//Xử lý thêm sản phẩm
[HttpPost]
public IActionResult Add(Product product, IFormFile ImageUrl)
{
if (ModelState.IsValid) //kiem tra hop le
{
if (ImageUrl != null)
{
//xu ly upload và lưu ảnh đại diện
product.ImageUrl = SaveImage(ImageUrl);
}
//thêm product vào table Product
_db.Products.Add(product);
_db.SaveChanges();
TempData["success"] = "Product inserted success";
return RedirectToAction("Index");
}
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View();
}
//Hiển thị form cập nhật sản phẩm
public IActionResult Update(int id)
{
var product = _db.Products.Find(id);
if (product == null)
{
return NotFound();
}
//truyền danh sách thể loại cho View để sinh ra điều khiển DropDownList
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View(product);
}
//Xử lý cập nhật sản phẩm
[HttpPost]
public IActionResult Update(Product product, IFormFile ImageUrl)
{
if (ModelState.IsValid) //kiem tra hop le
{
var existingProduct = _db.Products.Find(product.Id);
if (ImageUrl != null)
{
//xu ly upload và lưu ảnh đại diện mới
product.ImageUrl = SaveImage(ImageUrl);
//xóa ảnh cũ (nếu có)
if (!string.IsNullOrEmpty(existingProduct.ImageUrl))
{
var oldFilePath = Path.Combine(_hosting.WebRootPath,
existingProduct.ImageUrl);
if (System.IO.File.Exists(oldFilePath))
{
System.IO.File.Delete(oldFilePath);
}
}
}
else
{
product.ImageUrl = existingProduct.ImageUrl;
}
//cập nhật product vào table Product
existingProduct.Name = product.Name;
existingProduct.Description = product.Description;
existingProduct.Price = product.Price;
existingProduct.CategoryId = product.CategoryId;
existingProduct.ImageUrl = product.ImageUrl;
_db.SaveChanges();
TempData["success"] = "Product updated success";
return RedirectToAction("Index");
}
ViewBag.CategoryList = _db.Categories.Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.Name
});
return View();
}
private string SaveImage(IFormFile image)
{
//đặt lại tên file cần lưu
var filename = Guid.NewGuid().ToString() + Path.GetExtension(image.FileName);
//lay duong dan luu tru wwwroot tren server
var path = Path.Combine(_hosting.WebRootPath, @"images/products");
var saveFile = Path.Combine(path, filename);
using (var filestream = new FileStream(saveFile, FileMode.Create))
{
image.CopyTo(filestream);
}
return @"images/products/" + filename;
}
//Hiển thị form xác nhận xóa sản phẩm
public IActionResult Delete(int id)
{
var product = _db.Products.Find(id);
if (product == null)
{
return NotFound();
}
return View(product);
}
//Xử lý xóa sản phẩm
[HttpPost, ActionName("Delete")]
public IActionResult DeleteConfirmed(int id)
{
var product = _db.Products.Find(id);
if (product == null)
{
return NotFound();
}
// xoá hình cũ của sản phẩm
if (!String.IsNullOrEmpty(product.ImageUrl))
{
var oldFilePath = Path.Combine(_hosting.WebRootPath, product.ImageUrl);
if (System.IO.File.Exists(oldFilePath))
{
System.IO.File.Delete(oldFilePath);
}
}
// xoa san pham khoi CSDL
_db.Products.Remove(product);
_db.SaveChanges();
TempData["success"] = "Product deleted success";
//chuyen den action index
return RedirectToAction("Index");
}
}
}
I have no idea whats going on with my code. I can delete product but cant add or update it on database.
Im also searching for a lot solution on internet but seem i cant find which is the same as my problem.
Thanks for looking into this! Hope you guys a good day!