【发布时间】:2021-02-10 17:37:30
【问题描述】:
我显然不了解 Razor Pages 中模型绑定复杂属性的基本知识。当我的模型无效时,我 return Page(); 但在引用模型的复杂属性时出现异常。这是我所拥有的精简版:
型号:
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; }
}
索引.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>
当我将描述留空时,OnPost 中的模型无效并按预期返回Page()。但后来我在这里得到了System.NullReferenceException; Object reference not set to an instance of an object:
<h6>Directed by @Model.Movie.Director.Name</h6>
为什么Movie.Director 在这里为空?返回Page()时是否需要再次获取数据?我以为它会再次触发OnGet(),但事实并非如此。我做错了什么?
【问题讨论】:
-
OnGet()应该被解雇。我想知道它也不起作用的原因+1
标签: c# asp.net-core razor-pages