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