我试图弄清楚如何在asp.net Core Razor Pages中填充一个复选框列表。考虑以下类:
public class SignupPageModel
{
public string UserName { get; set; }
public string Password { get; set; }
public List<CheckBoxGroup> Hobbies{ get; set; }
}
public class CheckBoxGroup
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
然后从Page
中,我想从数据库中填充Hobbies
列表(为简化起见,对代码段进行了编辑):
public class SignupModel : PageModel
{
[BindProperty]
public SignupPageModel Input { get; set; }
public void OnGet()
{
var model = new SignupPageModel();
model.Hobbies = _repo.GetHobbiesCheckBoxGroup();
}
}
并在视图中显示:
@for (var i = 0; i < Model.Input.Hobbies.Count; i++)
{
<div class="form-check">
<input type="checkbox" asp-for="@Model.Input.Hobbies[i].IsSelected"/>
<label asp-for="@Model.Input.Hobbies[i].IsSelected">@Model.Input.Hobbies[i].Name</label>
<input type="hidden" asp-for="@Model.Input.Hobbies[i].Id"/>
<input type="hidden" asp-for="@Model.Input.Hobbies[i].Name"/>
</div>
}
但是渲染View
时出现以下错误:
NullReferenceException: Object reference not set to an instance of an object.
在这一行:
@for (var i = 0; i < Model.Input.Hobbies.Count; i++)
我要去哪里错了?
答案 0 :(得分:0)
万一其他人遇到同样的问题,解决方法是更改:
public class SignupModel : PageModel
{
[BindProperty]
public SignupPageModel Input { get; set; }
public void OnGet()
{
var model = new SignupPageModel();
model.Hobbies = _repo.GetHobbiesCheckBoxGroup();
}
}
对此:
public class SignupModel : PageModel
{
[BindProperty]
public SignupPageModel Input { get; set; }
public void OnGet()
{
Input = new SignupPageModel();
Input.Hobbies = _repo.GetHobbiesCheckBoxGroup();
}
}