如何在 Angular Typescript 中将数组作为表单数据发布

PNR*_*PNR 5 arrays http-post typescript asp.net-core-webapi angular

我正在 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);
    }
Run Code Online (Sandbox Code Playgroud)

locationSecondaryIds 是一个数字[]。

我也尝试过忽略 Blob 并将其作为 [1,1] 发送,但是当服务器到达服务器时,它无法将其转换为列表

有什么好的建议吗?

首先十分感谢 :-)

fin*_*s10 7

我也遇到过同样的情况,这就是我的做法。

我的 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);
}
Run Code Online (Sandbox Code Playgroud)

现在将其发布到 asp.net core web api,它应该可以工作。

我的服务器端 C# 类:

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);
}
Run Code Online (Sandbox Code Playgroud)

注意:确保[FromForm]在操作方法中使用修饰参数。

Asp.Net Core Web Api 控制器操作方法:

public class SomeClass
{
    public string Parameter1 { get; set; }
    public int Parameter2 { get; set; }
    public string[] ArrayValue { get; set; }
    public IFormFile[] Files { get; set; }
}
Run Code Online (Sandbox Code Playgroud)


小智 0

您可以尝试使用此方法选择多个复选框值并将其附加到表单数据中。在提交按钮上:

let subs = [];
subs = this.skillForm.value.subjects; // here subject refers to multi select dropdown
let subString = subs.toString(); // you can let the values to be int as per your DB 
//column
let fd = new FormData();
fd.append('values',subString);
Run Code Online (Sandbox Code Playgroud)