【问题标题】:Object Reference not set to an instance of object in asp.net mvc对象引用未设置为 asp.net mvc 中的对象实例
【发布时间】:2014-10-15 00:24:02
【问题描述】:

我正在创建属于类别模型的新产品。当我执行我的 Create 方法时,错误会调用它

“模型”对象上的“对象引用未设置为对象实例”

我的控制器类:

public ActionResult CreateProduct()   
{
    SetCateProductViewBag();
    return View(new CateProdViewModel());
}

[HttpPost]       
public ActionResult CreateProduct(CateProdViewModel model)
{

    var ValidImageTypes = new String[]
    {
        "image/gif",
        "image/jpeg",
        "image/jpg",
        "image/pjpeg",
        "image/png"
    };
    if (model.ImageUpload == null || model.ImageUpload.ContentLength == 0)
    {
        ModelState.AddModelError("ImageUpload", "This Field is required.");
    }
    else if (!ValidImageTypes.Contains(model.ImageUpload.ContentType))
    {
        ModelState.AddModelError("ImageUload", "Please choose either a GIF,jpg or png type of file.");
    }
    if (ModelState.IsValid)
    {

        var prod = new Product
        {
            //   CategoryName =model.category.CategoryName,
            //CategoryDescription=model.category.CategoryDescription,

            //CategoryId=model.CategoryId,
            ProductName = model.ProductName,
            ProductDescription = model.ProductDescription,
            Model = model.Model,
            ProductPrice = model.ProductPrice,
            AvailableForSale = model.AvailableForSale,
            Shippable = model.Shippable,
            AvailableStock = model.AvailableStock,
            ProductPicture = model.ProductPicture

        };
        SetCateProductViewBag(prod.CategoryId);
        if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0)
        {
            var UploadDir = "~/Uploads";
            var ImagePath = Path.Combine(Server.MapPath(UploadDir), model.ImageUpload.FileName);
            var ImageUrl = Path.Combine(UploadDir, model.ImageUpload.FileName);
            model.ImageUpload.SaveAs(ImagePath);
            prod.ProductPicture = ImageUrl;
        }
        productContext.product.Add(prod);
        productContext.SaveChanges();
        return RedirectToAction("CategoryIndex");
    }

    return View(model);
}

CateProdViewModel 类:

public class CateProdViewModel
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public string CategoryDescription { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public int AvailableStock { get; set; }
    public decimal ProductPrice { get; set; }
    public string Model { get; set; }
    public bool AvailableForSale { get; set; }
    public bool Shippable { get; set; }
    [DataType(DataType.ImageUrl)]
    public string ProductPicture { get; set; }
    public int SelectedValue { get; set; }
    [DataType(DataType.Upload)]
    public HttpPostedFileBase ImageUpload { get; set; }
    public virtual Category category { get; set; }
    [Display(Name="Product Categories")]
    public virtual ICollection<Category> categories { get; set; }
}

类别和产品的实体类:

public class Product
{
    public int ProductId { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public int AvailableStock { get; set; }
    public decimal ProductPrice { get; set; }
    public string Model { get; set; }
    public bool AvailableForSale { get; set; }
    public bool Shippable { get; set; }
    public string ProductPicture { get; set; }
    public int CustomerId { get; set; }
    public int CategoryId { get; set; }
    public virtual Category category { get; set; }

}

 public class Category
{
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public string CategoryDescription { get; set; }
    public virtual ICollection<Product> product { get; set; }

}

我的观点:

@model SmartShoppingCart.Models.CateProdViewModel

@{
  ViewBag.Title = "CreateProduct";
}

<h2>Create Product</h2>

<form action="" method="post" enctype="multipart/form-data">
    <div>
        @Html.LabelFor(m=>m.CategoryId,"Category")
        @Html.DropDownList("CategoryId",ViewBag.categories as SelectList, string.Empty)
        @Html.ValidationMessageFor(m=>m.CategoryId)
    </div>
    <div>
        @Html.HiddenFor(m=>m.CategoryId)
    </div>
    <div>
        @Html.LabelFor(m=>m.ProductName)
        @Html.TextBoxFor(m=>m.ProductName)
        @Html.ValidationMessageFor(m=>m.ProductName)
    </div>
     <div>
        @Html.LabelFor(m=>m.ProductDescription)
        @Html.TextBoxFor(m=>m.ProductDescription)
        @Html.ValidationMessageFor(m=>m.ProductDescription)
    </div>
     <div>
        @Html.LabelFor(m=>m.Model)
        @Html.TextBoxFor(m=>m.Model)
        @Html.ValidationMessageFor(m=>m.Model)
    </div>
    <div>
        @Html.LabelFor(m=>m.ProductPrice)
        @Html.TextBoxFor(m=>m.ProductPrice)
        @Html.ValidationMessageFor(m=>m.ProductPrice)
    </div>
     <div>
        @Html.LabelFor(m=>m.AvailableForSale)
        @Html.TextBoxFor(m=>m.AvailableForSale)
        @Html.ValidationMessageFor(m=>m.AvailableForSale)
    </div>
     <div>
        @Html.LabelFor(m=>m.Shippable)
        @Html.TextBoxFor(m=>m.Shippable)
        @Html.ValidationMessageFor(m=>m.Shippable)
    </div>
     <div>
        @Html.LabelFor(m=>m.AvailableStock)
        @Html.TextBoxFor(m=>m.AvailableStock)
        @Html.ValidationMessageFor(m=>m.AvailableStock)
    </div>
    <div>
        @Html.LabelFor(m=>m.ImageUpload)
        @Html.TextBoxFor(m => m.ImageUpload, new {type="file" })
    </div>
    <div>
         <button type="submit" value="Add" ></button>
    </div>
</form>

private void SetCateProductViewBag(int? CateId = null)
{
    if (CateId == null)
    {
        ViewBag.Categories = new SelectList(productContext.category, "CategoryId", "CategoryName");
    }
    else
    {
        ViewBag.Categories = new SelectList(productContext.category.ToArray(),"CategoryId","CategoryName",CateId);
    }
}

【问题讨论】:

  • 你在哪一行得到错误。这通常是您可以分辨的方式
  • 我在这一行收到错误:if (model.ImageUpload == null || model.ImageUpload.C​​ontentLength == 0)
  • model 必须为 null,或者 ContentLength 不是 int

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

您的错误发生是因为您的模型在回发时为空。该模型为空,因为它包含一个名为Model 的属性,并且操作方法的参数名称也名为model,这让可怜的DefaultModelBinder 感到困惑。要么将属性名称更改为其他名称,要么将您的 post action 方法中的参数名称更改为其他名称。

【讨论】:

  • 它现在工作正常。但现在 m 获得产品图片、类别的空值。而 CategoryId 和 ProductId 取 0 值。并且发生错误“INSERT 语句与 FOREIGN KEY 约束 \"FK_Product_Category1\" 冲突。冲突发生在数据库 \"ShoppingCart\"、表 \"dbo.Category\"、列 'CategoryId' 中。\r\n语句已终止。"}
  • 视图中有其他错误 - 我会检查并更新答案
  • CategoryID使用@Html.DropDownListFor(m =&gt; m.CategoryId, ViewBag.categories as SelectList),删除@Html.HiddenFor(m=&gt;m.CategoryId)。至于 ProductId 和 ProductPicture ,您似乎没有为这些属性呈现任何类型的 inputselect
【解决方案2】:

为什么不把第一个动作改成:

public ActionResult CreateProduct(CateProdViewModel model)   
{
    SetCateProductViewBag();
    return View(model);
}

您的DefaultModelBinder 将实例化模型,因此它永远不会为空。

除此之外,我需要知道您所说的When i execute my Create method 是什么意思。因为那里没有 Create 方法。你有CreateProduct,你有两个。这是POSTGET 请求吗?

【讨论】:

  • 是的,我在谈论 CreateProduct 操作方法。通过在获取发布请求中设置相同的参数,调用错误。它没有被执行。
猜你喜欢
  • 2020-04-13
  • 1970-01-01
  • 1970-01-01
  • 2013-07-26
  • 2013-10-28
  • 1970-01-01
  • 2018-09-07
  • 1970-01-01
  • 2021-09-14
相关资源
最近更新 更多