2013-12-15 73 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

相關問題