WebForms 手動 Request["field"] 取值繁瑣;MVC 雖支援模型綁定,但不原生支持 List<T> 批量綁定(同名字段多行)。
RequestToModel 靜態工具類<input name="id" value="1" /> <input name="sex" value="男" />
var model = RequestToModel.GetSingleForm<UserModel>();
// 或帶前綴:GetSingleForm<UserModel>("form1.")
<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="女" />
var list = RequestToModel.GetListByForm<UserModel>(); // 自動識別為 3 條記錄
private static List<T> SetList<T>(string prefix, int index) where T : new()
{
var list = new List<T>();
var props = new T().GetType().GetProperties();
// 以第 index 個屬性為基準,統計該字段在 Request 中出現的次數(逗號分隔)
int count = HttpContext.Current.Request[prefix + props[index].Name].Split(',').Length;
for (int i = 0; i < count; i++)
{
var entity = new T();
foreach (var p in props)
{
string raw = HttpContext.Current.Request[prefix + p.Name];
if (!string.IsNullOrEmpty(raw))
{
string val = raw.Split(',')[i];
p.SetValue(entity, Convert.ChangeType(val, p.PropertyType), null);
}
}
list.Add(entity);
}
return list;
}
name 必須與實體屬性名完全一致(不區分大小寫)。index=0)作為基準計數,若首字段可能為空,可重載指定 index。