Object引用未设置为asp.net mvc中的对象实例

时间:2014-08-21 11:25:37

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

我正在创建属于类别模型的新产品。当我执行我的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);
    }
}

2 个答案:

答案 0 :(得分:0)

为什么不将第一个操作更改为:

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

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

除此之外,我需要通过说When i execute my Create method来了解你的意思。由于您没有Create方法。你有CreateProduct,你有两个。这是POST还是GET请求?

答案 1 :(得分:0)

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