You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Asp.Net Core Razor Pages:列表对象绑定与文件上传问题

解决方案

1. 修复CSHTML中的控件命名问题

你当前用foreach循环生成的表单控件,无法生成带索引的字段名,导致ASP.NET Core的模型绑定无法识别每个Person项,最终People在Post时为null。需要改用for循环遍历列表,让asp-for生成符合绑定规则的命名格式(如People[0].Photo)。

修改后的Create.cshtml代码:

<form method="post" enctype="multipart/form-data">
    @for (int i = 0; i < Model.People.Count; i++)
    {
        <input type="hidden" asp-for="People[i].Id" />
        <input type="hidden" asp-for="People[i].Name" />
        <input type="file" asp-for="People[i].Photo" />
    }
    <button type="submit">提交</button>
</form>

修改后生成的文件输入框name属性会变成People[0].Photo、People[1].Photo这类格式,完全符合模型绑定的要求,能正确将表单数据映射到People列表。

2. 在OnPost方法中访问Photo属性

调整页面后,[BindProperty]修饰的People列表会被自动绑定,你可以直接遍历集合访问每个Person的Photo属性:

修改后的Create.cshtml.cs代码:

public class CreateModel : PageModel
{
    [BindProperty]
    public List<Person> People { get; set; }

    // 保留原OnGetAsync代码...

    public async Task<IActionResult> OnPostAsync()
    {
        if (!ModelState.IsValid)
        {
            // 验证失败时返回页面
            return Page();
        }

        foreach (var person in People)
        {
            if (person.Photo != null && person.Photo.Length > 0)
            {
                // 示例:处理上传的照片(保存到服务器)
                var fileName = Path.GetFileName(person.Photo.FileName);
                var savePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot/uploads", fileName);
                
                using (var stream = new FileStream(savePath, FileMode.Create))
                {
                    await person.Photo.CopyToAsync(stream);
                }
            }
        }

        // 处理完成后跳转(示例:返回列表页)
        return RedirectToPage("./Index");
    }
}

关键注意点

  • 必须在form标签中添加enctype="multipart/form-data",否则无法完成文件上传。
  • 集合类型的模型绑定,要求表单字段名必须包含索引(如People[index].PropertyName),这是模型绑定器识别集合项的核心规则。
  • 建议添加ModelState.IsValid检查,确保绑定的数据符合验证规则。

内容的提问来源于stack exchange,提问作者thampister

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 16:07:50