I have problem in my code. I try to Edit detail of product and add an field "Category" and "Publisher" as a DropdownList while update Detail like this image: here
This is my code in controller:
[HttpGet]
public IActionResult Edit_Products(string productId)
{
ViewBag.ListofPublisher = context.Publisher.ToList();
ViewBag.ListofCategory = context.Category.ToList();
return View(context.Product.Find(productId));
}
In the View,I add two dropdownList to loads Category and Publisher and post back to controller
<div class="form-group">
<label>Category</label>
<br />
<select class="form-control" asp-for="CategoryCode"
asp-items="@(new SelectList(ViewBag.ListofCategory,"CategoryCode","CategoryName"))">
</select>
</div>
@*Product Category*@
<div class="form-group">
<label>Publisher</label>
<br />
<select class="form-control" asp-for="PublisherCode"
asp-items="@(new SelectList(ViewBag.ListofPublisher,"PublisherCode","PublisherName"))">
</select>
</div>
@*Product Publisher*@
In Edit controller, I will update this to table
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Edit_Products(Product product,string productCode)
{
if (ModelState.IsValid)
{
Product result = context.Product.SingleOrDefault(p => p.ProductCode.Equals(product.ProductCode));
try
{
string proCode = product.ProductCode;
result.ProductCode = (product.CategoryCode) + (product.PublisherCode) + (proCode.Substring(proCode.Length - 2));
result.ProductName = product.ProductName;
result.Price = product.Price;
result.Quantity = product.Quantity;
result.AuthorName = product.AuthorName;
result.ReleaseYear = product.ReleaseYear;
result.Ver = product.Ver;
result.Used = product.Used;
result.Review = product.Review;
result.CategoryCode = product.CategoryCode;
result.PublisherCode = product.PublisherCode;
result.Picture = product.Picture;
context.SaveChanges();
}
catch (Exception exx)
{
ViewBag.Msg = exx.Message;
}
return RedirectToAction("Index", "Manage_Products");
}
return View();
}
Then I got this error:
ArgumentNullException: Value cannot be null. (Parameter 'items')
Please help me.
From what I see in the question I would assume that error happens on POST request when your model fails validation (i.e. ModelState.IsValid
is false
). If that is the case - you need to fill ListofPublisher
and ListofCategory
again cause the data you put in the ViewBag/ViewData is only available during the life-cycle of the request within which you populated it (read more here). i.e. call:
ViewBag.ListofPublisher = context.Publisher.ToList();
ViewBag.ListofCategory = context.Category.ToList();
Before return View();
in your POST method.