0

我正在创建一个网上商店,当我添加产品时一切正常,当我尝试编辑我的产品时,我在它们所属的类别上出现错误。

这是我的代码:

@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>

现在,当我实际更改它们时会发生此错误,而不是当我获得更改它们的视图时。它说我的 selectedSubcatID 或 Model.Subcats 为空。

但其中没有一个是:

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");
}

编辑

[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();
        }
    }
}
4

1 回答 1

0

我发现了这个问题,不确定发生了什么,但是当你有一天遇到这个问题时可能值得一试。

在我放入所有新属性的文件中,例如价格、名称等。我在模型中进行了验证。对价格的一项验证不正确。我把它注释掉了,它起作用了:

检查验证:

@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>

我不知道为什么我得到这个 nullreferenceexception 但我真的很高兴它得到了修复!感谢你们的支持。

于 2013-04-17T22:20:09.657 回答