Object reference not set to an instance of an object Exception thrown..(Null referenceException was unhandled by user code)
Model:
public class AboutMod
{
private List<int> divWidthList = new List<int>();
public List<int> DivWidthList { get; set; }
}
Control page:
public ActionResult About()
{
AboutMod Obj = new AboutMod();//model class name
for (int i = 20; i <= 100; i += 20)
{
Obj.DivWidthList.Add(10);//Run time Exception occurs here 开发者_如何学C
}
return View();
}
There is absolutely no relation between your private field divWidthList
and the public property DivWidthList
. The public property is never initialized. You could initialize it for example in the constructor of the class:
public class AboutMod
{
public AboutMod
{
DivWidthList = new List<int>();
}
public List<int> DivWidthList { get; set; }
}
or don't use an auto property:
public class AboutMod
{
private List<int> divWidthList = new List<int>();
public List<int> DivWidthList
{
get
{
return divWidthList;
}
set
{
divWidthList = value;
}
}
}
initialise Obj.DivWidthList
first before attempting to use it:
AboutMod Obj = new AboutMod();//model class name
Obj.DivWidthList = new List<int>();
for (int i = 20; i <= 100; i += 20)
{
Obj.DivWidthList.Add(10);//Run time Exception occurs here
}
精彩评论