【发布时间】:2019-09-27 15:56:39
【问题描述】:
我正在尝试发布 PersonViewModel 列表,只要 PersonViewModel 没有任何 IFormFile 属性,它就可以正常工作。
Razor 页面模型:
public class TestModel : PageModel
{
[BindProperty]
public PersonViewModel[] People { get; set; }
public void OnGet()
{
}
public void OnPost()
{
// Do something with People property
}
}
视图模型:
public class PersonViewModel
{
public string Name { get; set; }
public string LastName { get; set; }
}
HTML 表单:
<form method="post" enctype="multipart/form-data">
<input type="text" name="People[0].Name" class="form-control" />
<input type="text" name="People[0].LastName" class="form-control" />
<input type="text" name="People[1].Name" class="form-control" />
<input type="text" name="People[1].LastName" class="form-control" />
<button type="submit" class="btn btn-success">Submit</button>
</form>
但是,如果我将 IFormFile 添加到 ViewModel 并再次发布表单,则表单将无法到达发布操作方法。
视图模型:
public class PersonViewModel
{
public string Name { get; set; }
public string LastName { get; set; }
public IFormFile Photo { get; set; } = null;
}
HTML 表单:
<form method="post" enctype="multipart/form-data">
<input type="text" name="People[0].Name" class="form-control" />
<input type="text" name="People[0].LastName" class="form-control" />
<input type="file" name="People[0].Photo" class="form-control" />
<input type="text" name="People[1].Name" class="form-control" />
<input type="text" name="People[1].LastName" class="form-control" />
<input type="file" name="People[1].Photo" class="form-control" />
<button type="submit" class="btn btn-success">Submit</button>
</form>
项目版本:ASP.NET Core 2.2
项目模板:ASP.NET Razor 页面
我做错了什么还是与 asp.net 核心有关?
【问题讨论】:
-
在视图模型中,您的属性名称
IFormFile是ResumeFile,但在视图模型中您有Photo? -
@hassan.ef 对不起,我试图简化真正的代码。复制真实代码的时候忘记改属性名了。
-
解决方法是添加一个单独的
BindProperty类型为List<IFormFile>,以便您可以上传与PersonViewModel对象列表分开的文件列表 -
@JoshWithee 不幸的是,我在项目中使用的真实 ViewModel 具有多个 IFormFile 属性。我需要有强类型的 ViewModel 或至少有一个解决方法来检测每个 ViewModel 的相关文件。
-
相关问题:github.com/aspnet/Mvc/issues/7719github.com/aspnet/Mvc/issues/8527 看起来有人可能已经解决了?
标签: c# asp.net-core model-binding