ASP.NET Razor Pages中回传List<>集合为空的问题解决
问题原因
当前表单仅渲染了TimeEntry数据的文本内容,没有生成可被ASP.NET Core模型绑定识别的表单控件。POST提交时,请求中没有包含任何TimeEntry相关的参数,因此后端无法绑定到List数据,导致Count为0。
解决方案
1. 修正前端代码:生成带正确命名的表单控件
使用for循环替代foreach,为每个TimeEntry生成对应的隐藏域(或可见输入框),确保表单提交时能传递数据。模型绑定需要集合元素的name属性格式为集合名[索引].属性名(如TimeEntry[0].entryTime)。
修改后的前端代码:
@model IndexModel @{ ViewData["Title"] = "Home page"; } <form class="form-horizontal" method="post"> <table> @if (Model.TimeEntry != null) { @for (int i = 0; i < Model.TimeEntry.Count; i++) { <tr> <td> Entry Time: @Model.TimeEntry[i].entryTime <!-- 添加隐藏域传递entryTime值 --> <input type="hidden" asp-for="TimeEntry[i].entryTime" /> </td> </tr> } } </table> <button type="submit">Post</button> </form>
2. 修正后端代码:简化OnPost方法
移除OnPost方法的参数,直接使用已标记[BindProperty]的TimeEntry属性,避免参数名冲突,同时让模型绑定自动填充数据。
修改后的后端代码:
public class TimeEntry { public DateTime entryTime { get; set; } } public class IndexModel : PageModel { [BindProperty(SupportsGet = true)] public List<TimeEntry> TimeEntry { get; set; } public void OnGet() { // 初始化List,避免空引用 TimeEntry = new List<TimeEntry>(); var _timeEntry = new TimeEntry { entryTime = DateTime.Now }; TimeEntry.Add(_timeEntry); _timeEntry = new TimeEntry { entryTime = DateTime.Now.AddMinutes(10) }; TimeEntry.Add(_timeEntry); } public void OnPost() { Console.WriteLine(TimeEntry.Count); // 现在会输出2 } }
关键说明
asp-for标签助手会自动生成正确的name和value属性(如name="TimeEntry[0].entryTime"),确保模型绑定能识别集合数据。- 使用
for循环而非foreach是因为需要索引值来构建正确的控件命名,foreach无法提供索引,生成的控件name不符合集合绑定规则。 - 移除OnGet的参数,直接初始化模型的TimeEntry属性,代码更简洁且避免潜在的空引用问题。
内容的提问来源于stack exchange,提问作者Mark C
相关产品推荐
相关产品推荐

