I'm making a webshop and when I add products everything is going alright, when I try to edit my products I get an error on the category they are under.
this is my code:
@model WorkshopASPNETMVC_III_Start.ViewModels.ProductViewModel
//somecode
{
//view other text boxes
<div class="editor-field">
@Html.DropDownListFor(model => model.SelectedSubcatID, Model.Subcats)
@Html.ValidationMessageFor(model => model.SelectedSubcatID)
</div>
Now this error occurs when I actually change them, not when I get the view to change em. Its says my selectedSubcatID or Model.Subcats are null.
but not one of them is:
ProductViewModel viewModel = new ProductViewModel();
Product product = productDBController.getProduct(productId);
viewModel.Product = product;
viewModel.SelectedSubcatID = product.Subcat.subcat_id;
viewModel.Subcats = getSelectListSubcats();
return View(viewModel);
private SelectList getSelectListSubcats()
{
List<SubCategorie> subcats = subcatDBController.GetSubCats();
SubCategorie emptySubcat = new SubCategorie();
emptySubcat.subcat_id = -1;
emptySubcat.naam = "";
subcats.Insert(0, emptySubcat);
return new SelectList(subcats, "subcat_id", "Naam");
}
EDIT
[HttpPost]
public ActionResult WijzigProduct(ProductViewModel viewModel, HttpPostedFileBase file)
{
if (file == null)
{
MessageBox.Show("Product niet gewijzigd, geen plaatje geselecteerd!");
return RedirectToAction("NieuwProduct", "Beheer");
}
else
{
String path = "/Content/Images";
DirectoryInfo info = new DirectoryInfo(Server.MapPath(path));
if (!info.Exists)
{
info.Create();
}
String fullName = String.Format("/Content/Images/{0}", file.FileName);
file.SaveAs(Server.MapPath(fullName));
try
{
if (ModelState.IsValid)
{
viewModel.Product.Subcat = subcatDBController.getSubCat(viewModel.SelectedSubcatID);
productDBController.UpdateProduct(viewModel.Product, fullName);
return RedirectToAction("beheerPagina", "Beheer");
}
else
{
viewModel.Subcats = getSelectListSubcats();
return View(viewModel);
}
}
catch (Exception e)
{
ViewBag.FoutMelding = "Er is iets fout gegaan: " + e;
return View();
}
}
}