0

could anyone please tell me why am I getting null reference error when creating new element using Razor Pages. New item is being created using proper (selected) values, list is visible, but after sending post request it just crashes.

I am using tag helpers:

<select asp-for="@Model.Book.AuthorId" asp-items="@(new SelectList(Model.AuthorsList, "AuthorId", "AuthorName"))"></select>

ViewModel looks like this:

public class BookCreateViewModel
{
    public Book Book { get; set; }
    public IEnumerable<Author> AuthorsList { get; set; }
}

Yes, the idea is to create new book using previously created authors.

Progman
  • 16,827
  • 6
  • 33
  • 48
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Progman May 21 '20 at 19:05
  • @Progman thanks, but it does not answer my question. Why is there a null exception if the list is created and displayed properly? And what I can't understand the most, is that new book is created in db. – pavel_jd84 May 21 '20 at 19:12
  • It might help to post the code that is called when you post the request. – colinD May 21 '20 at 21:16

2 Answers2

0

please AuthorsList null able

  <select asp-for="@Model.Book.AuthorId" asp-items="@(new SelectList(Model.?AuthorsList, "AuthorId", "AuthorName"))"></select>

    public class BookCreateViewModel`{
public Book Book { get; set; }
public IEnumerable<Author>? AuthorsList { get; set; }

}`

0

OK, so, the problem was I left blank view as a result of post method in controller, which obviously was causing null exception error.