萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> ASP.NET 程式設計

ASP.NET 表單陣列自動繫結到 List<T>:RequestToModel 批次處理多筆資料

突破單一物件限制:同名表單欄位自動轉為集合

HTML 表單允許同名欄位 (如 `name="id"` 出現多次),瀏覽器以逗號分隔傳送 (`id=1,2,3`)。`RequestToModel` 解析此格式,自動產生 `List`,支援批次編輯/新增場景。

表單結構範例

<!-- 批次編輯三筆資料 -->
<input name="id" value="1"> <input name="sex" value="男">
<input name="id" value="2"> <input name="sex" value="女">
<input name="id" value="3"> <input name="sex" value="女">

<!-- 瀏覽器送出:id=1,2,3&sex=男,女,女 -->

RequestToModel 核心實作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel;

public static class RequestToModel
{
    public static T GetSingleForm() where T : new()
        => GetSingleForm(null);

    public static T GetSingleForm(string prefix) where T : new()
        => SetList(prefix, 0).Single();

    public static List GetListByForm() where T : new()
        => GetListByForm(null);

    public static List GetListByForm(string prefix) where T : new()
        => SetList(prefix, 0);

    private static List SetList(string prefix, int keyIndex) where T : new()
    {
        var list = new List();
        try
        {
            var props = new T().GetType().GetProperties();
            if (props.Length == 0) return list;
            
            var keyProp = props[keyIndex];
            string keyName = prefix + keyProp.Name;
            string keyValues = HttpContext.Current.Request[keyName];
            if (String.IsNullOrEmpty(keyValues)) return list;
            
            int count = keyValues.Split(',').Length;
            
            for (int i = 0; i < count; i++)
            {
                var model = new T();
                foreach (var prop in props)
                {
                    string formKey = prefix + prop.Name;
                    string raw = HttpContext.Current.Request[formKey];
                    if (String.IsNullOrEmpty(raw)) continue;
                    
                    string val = raw.Split(',')[i];
                    if (String.IsNullOrEmpty(val)) continue;
                    
                    // 型別轉換
                    var converter = TypeDescriptor.GetConverter(prop.PropertyType);
                    object converted = converter.CanConvertFrom(typeof(string))
                        ? converter.ConvertFromInvariantString(val)
                        : Convert.ChangeType(val, prop.PropertyType);
                    
                    prop.SetValue(model, converted);
                }
                list.Add(model);
            }
        }
        catch (Exception ex)
        {
            // 記錄日誌
        }
        return list;
    }
}

使用範例

// 單一物件
var category = RequestToModel.GetSingleForm();

// 批次集合
var categories = RequestToModel.GetListByForm();

// 帶前綴 (如表單在 UserControl 中:name="ucCategory.id")
var categories = RequestToModel.GetListByForm("ucCategory.");

實體類別定義

public class Category
{
    public int Id { get; set; }
    public string Sex { get; set; }
    // 其他屬性...
}

限制與注意事項

限制說明因應
所有欄位筆數必須一致缺值會導致索引錯位前端補空值 `value=""` 或用隱藏欄位佔位
第一個屬性作為基準鍵類別屬性順序影響結果明確指定 `keyIndex` 或加 `[Key]` Attribute 判斷
不支援巢狀物件/集合扁平化結構複雜結構改用 JSON 傳輸 + Newtonsoft.Json 反序列化
檔案上傳Request.Files 不在 Params 中單獨處理 `Request.Files`

現代替代:JSON POST + Model Binding

// 前端
fetch('/api/categories/batch', {
    method: 'POST',
    headers: {'Content-Type': 'application/json'},
    body: JSON.stringify([
        {id:1, sex:'男'},
        {id:2, sex:'女'}
    ])
});

// 後端 (ASP.NET Core / MVC 4.5+)
[HttpPost]
public IActionResult Batch([FromBody] List categories) { ... }

適用場景: 傳統 Web Forms 大量編輯 Grid、Excel 匯入對應、舊系統無法改用 AJAX/JSON 時的快速方案。新專案請直接採用 JSON API + 前端框架。

copyright © 萬盛學電腦網 all rights reserved