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

标签 arrays angular typescript http-post asp.net-core-webapi

我在 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/

相关文章:

带有模拟结构指令的 Angular 测试组件失败

html - ngx-owl-carousel 单个元素占用所有宽度的情况

python - 为 NN 混洗两个 numpy 数组

javascript - 如何在 JavaScript 中获取两个数组之间的差异?

C - 将重复的数组记录写入文本文件

angular - 带有嵌套模块的嵌套路由

typescript - 如何在不扩展的情况下覆盖 TypeScript 接口(interface)?

node.js - docker : MongooseError [MongooseServerSelectionError]: getaddrinfo ENOTFOUND mongo

node.js - 如何开 Jest 模拟 Nestjs 导入?

php - 这个查询被过度转义了!需要一个简单的想法