Html.HiddenFor helper 抛出空异常



我想从模型中传递一个值...

@Html.HiddenFor(model => model.ProductId)

抛出的异常:System.Web.Mvc 中的"System.ArgumentException.dll

其他信息:值不能为 null 或空。

但它抛出了这个异常,我不知道为什么......没有 ProductId 不为空。

行动

   [HttpGet]
    public ActionResult Edit(int ProductId = 0)
    {
        PCsViewModel pcViewModel = new PCsViewModel();
        ProductRepository productRepo = new ProductRepository();
        Product dbProduct = productRepo.GetAll(item=>item.ID==ProductId);
        PCsRepository pcsRepo = new PCsRepository();
        PC dbPC = pcsRepo.GetAll(item=>item.ProductID==ProductId);
        if (dbProduct != null && dbPC != null)
        {
            pcViewModel = new PCsViewModel(dbProduct,dbPC);
        }
        return View(pcViewModel);
    }

视图模型

public int ProductId { get; set; }
        [Required]
        public string Name { get; set; }
        public string PCsInfo { get; set; }//for the front view
        [Required]
        public double Price { get; set; }
        [Required]
        public string ImagePath { get; set; }
        [Required]
        public string Processor { get; set; }
        [Required]
        public string OS { get; set; }
        [Required]
        public int RAM { get; set; }
        [Required]
        public int Storage { get; set; }
        [Required]
        public string VideoCard { get; set; }
        [Required]
        public int CategoryID { get; set; }
        public PCsViewModel()
        {
        }
        public PCsViewModel(Product product, PC pc)
        {
            this.ProductId = product.ID;
            this.CategoryID = product.CategoryID;
            this.OS = product.OS;
            this.Processor = product.Processor;
            this.Name = product.Name;
            this.RAM = product.RAM;
            this.Storage = product.Storage;
            this.VideoCard = pc.VideoCard;
            this.PCsInfo = "PC "+product.Name + "with processor " + product.Processor;
            this.Price = (double)product.Price;
            this.ImagePath = Path.Combine(Constants.ImagesPCsDirectory, product.ImageName);
        }

根据评论中的讨论,看起来您的实际问题与ProductId属性无关,而是与ImagePath属性有关,该属性被传递到Url.Content()帮助程序(以解决适当的路径(。

如果路径存在,这将按预期工作,但如果该属性为 null 或空,您将收到当前ArgumentNullException。最好的方法可能是仅在特定属性不为 null 仅呈现特定路径:

@if (!string.IsNullOrEmpty(Model.ImagePath)) {
    // Use Url.Content(Model.ImagePath) within here safely
}

有多种不同的方法可以处理此问题,例如在模型上添加其他属性来清理问题:

public bool HasImage => !string.IsNullOrEmpty(ImagePath);

然后使用:

@if (Model.HasImage) {
    // Use Url.Content(Model.ImagePath) within here safely
}

最新更新