对象引用未设置为对象的实例-错误消息

时间:2018-08-29 12:55:16

标签: c# asp.net-mvc

以下条件在失败NullReferenceException后返回View时抛出ModelState.Invalid

[HttpPost]
        [ActionName("Create")]
        public ActionResult Create(Item model)
        {
            string s = model.Category.Name;
            if (ModelState.IsValid && model.imageUpload != null && model.imageUpload.ContentLength > 0)
            {
                string initialPath = string.Format("~/Images/Products/" + s + "/"); // "~/Products/Images/Air Jordan/"
                var virtualPath = Path.Combine(initialPath, model.imageUpload.FileName); // ~/Products/Air Jordan/1.jpg                 
                var d = Directory.CreateDirectory(string.Format(Server.MapPath(initialPath))); // "D:\\Visual Studio Projects\\OnlineStore\\OnlineStore\\Products\\Air Jordan\\"             
                var extension = Path.GetExtension(model.imageUpload.FileName);                
                var validImageTypes = new[] { ".gif", ".GIF", ".jpg", ".JPG", ".jpeg", ".JPEG", ".pjpeg", ".PJPEG", ".png", ".PNG" };
                if (!validImageTypes.Contains(extension))
                {
                    ModelState.AddModelError("imageUpload", "Please add a valid format picture (i.e., a .gif,.jpg or .png image");
                    return View();
                }
                model.imageUpload.SaveAs(Server.MapPath(virtualPath));
                model.imageUrl = virtualPath;
                if (ModelState.IsValid)
                {
                    db.Items.Add(model);
                    db.SaveChanges();
                    TempData["name"] = model.ItemName;
                    return RedirectToAction("Create");
                }
            }
            model.Categories = new SelectList(db.Categories.ToList(), "Name", "Name");
            model.Brands = new SelectList(db.Brands.ToList(), "Name", "Name");
            return View();
        }

在调试器内部,执行在条件(model.Categories = new SelectList(db.Categories.ToList(), "Name", "Name");失败后跳到代码的最后三行(if (ModelState.IsValid && model.imageUpload != null && model.imageUpload.ContentLength > 0)),然后在填充View后无法返回CategoriesBrands来自数据库的列表。代码执行正在按预期运行,但是如果HtmlValidationMessages失败,我需要View出现在ModelState.IsValid上。但是显示以下错误消息:
Server Error in '/' Application. Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 19: @Html.LabelFor(model => model.Category.Name, "Category", htmlAttributes: new { @class = "control-label col-md-2" }) Line 20: <div class="col-md-10"> Line 21: @Html.DropDownListFor(model => model.Category.Name, Model.Categories, "--Please select an option--", htmlAttributes: new { @class = "form-control" }) Line 22: @Html.ValidationMessageFor(model => model.Category.Name, "", new { @class = "text-danger" }) Line 23: </div>

Source File: D:\Visual Studio

Projects\OnlineStore\OnlineStore\Views\Products\Create.cshtml Line: 21

模型类是:

Item类:

using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Web;
using System.Web.Mvc;

namespace OnlineStore.Models
{
    public class Item
    {
        [Key]
        public virtual int ItemID { get; set; }
        public virtual int CategoryID { get; set; }
        public virtual int BrandID { get; set; }
        [DisplayName("Product Name")]
        [Required(ErrorMessage = "Product name is required")]
        public virtual string ItemName { get; set; }
        [DisplayName("Product Price")]
        public virtual decimal ItemPrice { get; set; }
        public virtual Category Category { get; set; }
        //public virtual string CategoryName { get; set; }
        public virtual Brand Brand { get; set; }
        [DataType(DataType.ImageUrl)]
        [Display(Name = "Image URL")]
        public string imageUrl { get; set; }

        [NotMapped]
        [DataType(DataType.Upload)]
        [DisplayName ("Image Upload")]
        public HttpPostedFileBase imageUpload { get; set; }
        public IEnumerable<SelectListItem> Categories { get; set; }
        public IEnumerable<SelectListItem> Brands { get; set; }       

    }
}

Category类:

using System.Collections.Generic;
using System.ComponentModel;

namespace OnlineStore.Models
{
    public class Category
    {
        public virtual int? CategoryID { get; set; }
        [DisplayName("Category Name")]
        public virtual string Name { get; set; }
        public virtual List<Item> Items { get; set; }
    }
}

有人可以指导吗?

谢谢

0 个答案:

没有答案