我在 Angular 8 中工作,并在 .net core 2.2 中使用 web.api
我有一个表单,其中包括一些“常规”输入、一个文件和多个可选择的复选框。
问题是多选复选框,我把它变成了一个数字数组。在我将数据发布到服务器之前,我将我的 FormGroup 转换为 FormData 并手动添加文件以及来自多选复选框的整数数组:
data.append('locationsSecondaryIds',
new Blob( [ JSON.stringify(this.profilePersonalData.locationsSecondaryIds)], { type : 'application/json' } ) );
if (this.file) {
data.append('document', this.file, this.file.name);
}
locationsSecondaryIds 是一个数字[]。
我也尝试过省略 Blob 并将其作为 [1,1] 发送,但是当服务器到达服务器时它无法将其转换为列表
有什么好的建议吗?
提前致谢:-)
最佳答案
我遇到了同样的情况,这就是我的做法。
我在 Angular 中的 component.ts 文件:
const formData = new FormData();
formData.append('Parameter1', "Some String Value");
formData.append('Parameter2', this.currentUserId.toString());
for (const index in this.arrayValues)
{
// instead of passing this.arrayValues.toString() iterate for each item and append it to form.
formData.append(`ArrayValue[${index}]`,this.arrayValues[index].toString());
}
for (const file of this.importedFiles)
{
formData.append('Files', file);
}
现在将其发布到 asp.net core web api,它应该可以工作。
我的服务器端 C# 类:
public class SomeClass
{
public string Parameter1 { get; set; }
public int Parameter2 { get; set; }
public string[] ArrayValue { get; set; }
public IFormFile[] Files { get; set; }
}
Note: Make sure to decorate your parameter with
[FromForm]
in your action method.
Asp.Net Core Web Api Controller 操作方法:
public async Task<IActionResult> SomeMethod([FromForm] SomeClass someClass)
{
...
}
关于arrays - 如何在 Angular Typescript 中将数组作为表单数据发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59004833/