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=男,女,女 -->
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` |
// 前端
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 + 前端框架。