gpt4 book ai didi

c# - 如何在 asp.net Core Razor Pages 中填充复选框列表?

转载 作者:太空宇宙 更新时间:2023-11-03 14:39:11 24 4
gpt4 key购买 nike

我正在尝试了解如何在 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();
}
}

并在 View 中显示:

@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++)

我哪里错了?

最佳答案

如果其他人遇到同样的问题,解决方法是更改​​:

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

关于c# - 如何在 asp.net Core Razor Pages 中填充复选框列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58249674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com