ค้นหาเว็บไซต์

วิธีส่งอาเรย์เป็นข้อมูลฟอร์มใน Angular Typescript


ฉันกำลังทำงานกับ Angular 8 และกำลังใช้ web.api ใน .net core 2.2

ฉันมีแบบฟอร์มที่รวมถึงอินพุต "ปกติ" บางรายการ ไฟล์ และกล่องกาเครื่องหมายที่สามารถเลือกหลายตัวได้

ปัญหาคือกล่องกาเครื่องหมายที่เลือกได้หลายตัว ซึ่งฉันเปลี่ยนเป็นอาร์เรย์ของตัวเลข ก่อนที่ฉันจะส่งข้อมูลไปยังเซิร์ฟเวอร์ ฉันจะแปลง 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 เป็น number[]

ฉันก็ลองไม่ใส่ Blob แล้วส่งมันเป็น [1,1] แต่เมื่อเซิร์ฟเวอร์ได้รับมัน เซิร์ฟเวอร์ไม่สามารถแปลงมันเป็น List ได้

มีคำแนะนำดีๆ บ้างไหม?

ขอบคุณมากล่วงหน้าครับ/ค่ะ :-)

คำตอบ #1

ฉันเจอสถานการณ์เดียวกันและนี่คือวิธีที่ฉันทำ

ไฟล์ component.ts ของฉันใน Angular:

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; }
}

หมายเหตุ: ตรวจสอบให้แน่ใจว่าได้ตกแต่งพารามิเตอร์ของคุณด้วย [FromForm] ในเมธอดแอ็กชันของคุณ

เมธอดแอคชันของคอนโทรลเลอร์ Asp.Net Core Web Api:

public async Task<IActionResult> SomeMethod([FromForm] SomeClass someClass)
{
    ...
}

คำตอบ #2

คุณสามารถลองใช้สิ่งนี้สำหรับการเลือกค่าหลายช่องทำเครื่องหมายและนำไปเพิ่มในข้อมูลฟอร์ม เมื่อกดปุ่มส่ง:

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);

บทความที่เกี่ยวข้อง