I'm apparently not understanding something fundamental about model binding complex properties in Razor Pages. When my model isn't valid, I return Page(); but I get an exception when referencing a complex property of the model. Here's a slim version of what I have:
Models:
public class Movie
{
public int Id { get; set; }
public string Title { get; set; }
public Director Director { get; set; }
public string Description { get; set; }
}
public class Director
{
public int Id { get; set; }
public string Name { get; set; }
}
Index.cshtml.cs:
[BindProperty]
public Movie Movie { get; set; }
[BindProperty, Required]
public string Description { get; set; }
public IActionResult OnGet()
{
// Pretend we're loading from the DB...
Movie = new Movie
{
Id = 1,
Title = "Citizen Kane",
Director = new Director
{
Id = 101,
Name = "Orson Wells"
}
};
return Page();
}
public IActionResult OnPost()
{
if (!ModelState.IsValid)
return Page();
Movie.Description = Description;
//Save to DB
// ...
return RedirectToPage("/Index");
}
Index.cshtml:
@page
@model IndexModel
<h5>@Model.Movie.Title</h5>
<h6>Directed by @Model.Movie.Director.Name</h6>
<form method="post">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<input type="hidden" asp-for="Movie.Id" />
<textarea asp-for="Description" placeholder="Enter Description"></textarea>
<button type="submit">Submit</button>
</form>
When I leave Description blank, the model is invalid in OnPost and returns Page() as expected. But then I get a System.NullReferenceException; Object reference not set to an instance of an object here:
<h6>Directed by @Model.Movie.Director.Name</h6>
Why is Movie.Director null here? Do I have to get the data again when returning Page()? I was thinking it would fire OnGet() again but it doesn't. What am I doing wrong?