2013-12-15 158 views
1

每当我尝试向模型中添加新对象时,都会收到错误我收到此错误“对象引用未设置为对象的实例”。不知道为什么我总是创建一个新的对象。NullReferenceException未将对象引用设置为对象的实例。添加到模型

我有包括的型号:

public class Model 
{ 
    public IList<Model1> Something { get; set; } 
    public IList<Model2> Something1 { get; set; } 
} 

我也有我的控制器:

 Model model = new Model(); 

     HttpCookie cookie = Request.Cookies["Login"]; 
     if (cookie != null) 
     { 
      int ID = int.Parse(cookie["ID"]); 

      var DBInfo = db.Details(ID); 
      foreach (var info in DBInfo) 
      { 
       Something1 model1 = new Something1(); 
       model1.ID = ID; 
       model1.FullName = info.FullName; 
       model1.CourseCode = info.CourseCode; 
       model.Something1.Add(model1); 

      } 

错误弹出,当我加入这个MODEL1模型

+0

几乎'NullReferenceException'的所有情况都是一样的。请参阅“[什么是.NET一个NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)”获得一些提示。 –

+0

我确实看到了,但coudln't不知道为什么我的代码犯了错误,因为我以为我正在使用这条线创建一个新对象“Something1 model1 = new Something1();”,但似乎我必须创建一个新列表以添加我没有意识到的东西。 – user1938460

回答

3

你必须在使用前初始化Something1字段,如下所示:

model.Something1 = new List<Model2>(); 

或者初始化模型时:

Model model = new Model 
{ 
    Something = new List<Model1>(), 
    Something1 = new List<Model2>() 
}; 
+1

谢谢,我以为我在初始化时调用“Something1 model1 = new Something1();” – user1938460

相关问题