Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

แปลง JavaScript Array เป็น C# Array - Web Development

การส่งข้อมูล Array จาก JavaScript (Client-side) ไป C# (Server-side) ทำได้หลายวิธี ขึ้นอยู่กับ Architecture

วิธีที่ 1: Form Submit / Hidden Field (Traditional)

// JavaScript
var myArr = ["Welcome", "to", "the", "Web", "World"];
document.getElementById('hiddenArray').value = myArr.join(',');

// HTML


// C# Controller (ASP.NET Core)
public IActionResult Receive(string arrayData)
{
    if (string.IsNullOrEmpty(arrayData)) return BadRequest();

    string[] arr = arrayData.Split(',', StringSplitOptions.RemoveEmptyEntries);
    // arr = ["Welcome", "to", "the", "Web", "World"]
}

วิธีที่ 2: AJAX / Fetch + JSON (Modern - แนะนำ)

// JavaScript (Fetch API)
const myArr = ["Welcome", "to", "the", "Web", "World"];

fetch('/api/receive', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(myArr)
});

// C# Controller (ASP.NET Core)
[HttpPost]
public IActionResult Receive([FromBody] string[] arrayData)
{
    // Model Binding แปลง JSON Array → string[] อัตโนมัติ
    // arrayData = ["Welcome", "to", "the", "Web", "World"]
    return Ok(new { Count = arrayData.Length });
}

วิธีที่ 3: Complex Object Array

// JavaScript
const users = [
    { id: 1, name: "Alice", active: true },
    { id: 2, name: "Bob", active: false }
];

fetch('/api/users', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(users)
});

// C# DTO
public class UserDto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public bool Active { get; set; }
}

// Controller
[HttpPost]
public IActionResult ReceiveUsers([FromBody] UserDto[] users)
{
    // users เป็น UserDto[] แล้ว
}

วิธีที่ 4: Query String (สำหรับ Array เรียบง่าย)

// JavaScript
const ids = [1, 2, 3, 4, 5];
const url = '/api/items?' + ids.map(id => `ids=${id}`).join('&');
// /api/items?ids=1&ids=2&ids=3&ids=4&ids=5

// C# - Model Binding รองรับอัตโนมัติ
public IActionResult GetItems([FromQuery] int[] ids)
{
    // ids = [1,2,3,4,5]
}

Blazor (WebAssembly) - JavaScript Interop

// C# (Blazor Component)
@inject IJSRuntime JS

private async Task ReceiveFromJS()
{
    // JavaScript Function คืนค่า Array
    string[] arr = await JS.InvokeAsync("getMyArray");
    // หรือ
    int[] numbers = await JS.InvokeAsync("getNumbers");
}

// JavaScript
window.getMyArray = () => ["Welcome", "to", "WebAssembly"];
window.getNumbers = () => [1, 2, 3, 4, 5];

SignalR - Real-time Array Transfer

// Client (JS)
connection.invoke("SendArray", ["A", "B", "C"]);

// Server (Hub)
public async Task SendArray(string[] items)
{
    await Clients.All.SendAsync("ReceiveArray", items);
}

สรุปแนะนำ

ScenarioMethodFormat
Traditional Form PostHidden Field + SplitCSV String
SPA / AJAX / Modern WebFetch + JSONJSON Array
Blazor WASMJS InteropAuto Marshaling
Real-timeSignalRAuto Marshaling
Simple GETQuery StringRepeated Keys

⚠️ Security Note

  • Validate Array Size (Prevent DoS)
  • Validate Each Element (XSS, Injection)
  • Use `[FromBody]` with JSON для Complex Types
  • Limit Request Size: `services.Configure(o => o.ValueLengthLimit = ...)`