0
我有一定的要求,其中我需要從數組指定字符串值,以我的一般模型屬性列表,但不能訪問該模型的結構和得到以下錯誤:
無法訪問泛型列表C#MVC 4
NullReferenceException was unhandled by user code. Object reference not set to an instance of an object.
我的模型結構如下:
namespace ExamEvent.Models
{
public class Author
{
public string AuthId { get; set; }
public string AuthName { get; set; }
public List<Books> AuthBooks { get; set; }
}
public class Books
{
public string BookId { get; set; }
public string BookName { get; set; }
}
}
注:我創建圖書清單。
在我的控制器中,我試過以下(包括註釋行):
我在foreach中出現上述錯誤。
public ActionResult Index()
{
Author author = new Author();
string[] bookId = {"30", "43", "44", "56", "45"};
foreach (var item in bookId)
{
author.AuthBooks[0].BookId = item;
//author.AuthBooks[author.AuthBooks.IndexOf(item)].BookId
}
return View(author);
}
您需要實例'AuthBooks'。這個問題非常有規律地問:http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – Steve
因爲'AuthBooks'是'null' - 你需要初始化它。 –