我正在使用一个类模型,其中我声明了一个相同类类型的列表。 但是当我要在这个列表中赋值时,它给对象引用null异常,而我在分配给这个列表的参数中有一些值。
public class BackSplashTileGuideViewModel
{
public int ID { get; set; }
public Nullable<int> ProductID { get; set; }
public string ProductDescription { get; set; }
[Required(ErrorMessage ="Required")]
public string Imagepath { get; set; }
public string UpdateImagepath { get; set; }
[Required(ErrorMessage = "Required")]
public string[] Products { get; set; }
public string MultipleProduct { get; set; }
public string ProductsName { get; set; }
public int CreatedBy { get; set; }
public System.DateTime CreatedOn { get; set; }
public Nullable<int> UpdatedBy { get; set; }
public Nullable<System.DateTime> UpdatedOn { get; set; }
public string Status { get; set; }
public List<BackSplashTileGuideViewModel> lstBacksplashTile { get; set; }
}
public ActionResult BacksplashTileInfo()
{
if (Session["BacksplashTileID"] != null)
{
_websiteRepo = new WebsiteRepo();
_adminRepo = new AdminRepo();
string Name = "Backsplash & Wall Tile";
int MasterDetailID = _adminRepo.GetMasterDetailIDByName(Name);
var AllProducts = _adminRepo.GetAllProductsName().Where(x => x.ProductGroupID == MasterDetailID).ToList();
int id = Convert.ToInt32(Session["BacksplashTileID"]);
var BacksplashProduct = _websiteRepo.GetBacksplashTileByID(id);
if(BacksplashProduct != null)
{
var products = BacksplashProduct.MultipleProduct.Split(',');
for (int i = 0; i < products.Length; i++)
{
var detail = AllProducts.Where(x => x.ID == Convert.ToInt32(products[i])).Select(y => new {y.ID ,y.ProductName,y.Descriptions }).FirstOrDefault();
BacksplashProduct.ProductID = detail.ID;
BacksplashProduct.ProductDescription = detail.Descriptions;
BacksplashProduct.ProductsName = detail.ProductName;
BacksplashProduct.lstBacksplashTile.Add(BacksplashProduct);
}
return View(BacksplashProduct);
}
else
{
return RedirectToAction("BacksplashTileGuide", "Home");
}
}
else
{
return RedirectToAction("BacksplashTileGuide", "Home");
}
}
答案 0 :(得分:5)
我认为这会对你有帮助。
在向其中添加内容之前,您必须将内存分配给列表。
if(BacksplashProduct != null)
{
//YOu missed assignment here
BacksplashProduct.lstBacksplashTile = new List<BackSplashTileGuideViewModel>();
var products = BacksplashProduct.MultipleProduct.Split(',');
for (int i = 0; i < products.Length; i++)
{
var detail = AllProducts.Where(x => x.ID == Convert.ToInt32(products[i])).Select(y => new {y.ID ,y.ProductName,y.Descriptions }).FirstOrDefault();
BacksplashProduct.ProductID = detail.ID;
BacksplashProduct.ProductDescription = detail.Descriptions;
BacksplashProduct.ProductsName = detail.ProductName;
BacksplashProduct.lstBacksplashTile.Add(BacksplashProduct);
}
return View(BacksplashProduct);
}