0

I have a certain requirement wherein I need to assign string values from array to my generic model attribute list, but not able to access the model structure and getting the following error:

NullReferenceException was unhandled by user code. Object reference not set to an instance of an object.

My model structure is as follows:

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; }
    }
}

Note: I've created List of Books.

In my controller I've tried the following (including the commented line):
I'm getting above error in 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);
}
Denver Gomes
  • 44
  • 1
  • 12
  • You need to instantiate `AuthBooks`. And this question is asked extremely regularly: http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it – Steve Mar 05 '16 at 12:08
  • Because `AuthBooks` is `null` - you need to initialize it. –  Mar 05 '16 at 12:08

1 Answers1

1
    author.AuthBooks = new List<Book>();
    foreach (var item in bookId)
    {
        author.AuthBooks.Add(new Book {bookId = item, BookName = "bookName"});
    }
Backs
  • 24,430
  • 5
  • 58
  • 85