/// <summary>
/// 从提交表单中通过反射获取多个对象
/// </summary>
/// <typeparam name="T">对象的类</typeparam>
/// <param name="prefix">表单前缀</param>
/// <param name="index">以第对象的几个字段作为基准,这个字段要求在提交的数据中必须存在</param>
/// <param name="ignoreCase">是否忽略大小写,默认是忽略大小写</param>
/// <returns>指定对象的列表</returns>
private static List<T> GetList<T>(string prefix, int index = 0, bool ignoreCase = true) where T : new()
{
List<T> t = new List<T>();
Dictionary<string, List<string>> paras = new Dictionary<string, List<string>>();
System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
#region 将提交上来的键值对数据放到字典里面
foreach (var key in request.QueryString.AllKeys)
{
string KEY = key;
if (ignoreCase)
KEY = key.ToUpper();
if (paras.ContainsKey(KEY))
{
string[] values = request.QueryString.GetValues(key);
paras[KEY].AddRange(values);
}
else
{
List<string> values = new List<string>();
values.AddRange(request.QueryString.GetValues(key));
paras.Add(KEY, values);
}
}
foreach (string key in request.Form.AllKeys)
{
string KEY = key;
if (ignoreCase)
KEY = key.ToUpper();
if (paras.ContainsKey(KEY))
{
string[] values = request.Form.GetValues(key);
paras[KEY].AddRange(values);
}
else
{
List<string> values = new List<string>();
values.AddRange(request.Form.GetValues(key));
paras.Add(KEY, values);
}
}
#endregion
try
{
var properties = new T().GetType().GetProperties();
var keyName = prefix + properties[index].Name;
if(ignoreCase)
keyName = keyName.ToUpper();
var subNum = paras[keyName].Count;
for (int i = 0; i < subNum; i++)
{
var model = new T();
foreach (var p in properties)
{
keyName = prefix + p.Name + "";
if (ignoreCase)
keyName = keyName.ToUpper();
if (paras.ContainsKey(keyName) && paras[keyName].Count > i)
{
string pval = paras[keyName][i];
// We need to check whether the property is NULLABLE
if (p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
{
p.SetValue(model, Convert.ChangeType(pval, p.PropertyType.GetGenericArguments()[0]), null);
}
else
{
p.SetValue(model, Convert.ChangeType(pval, p.PropertyType), null);
}
}
}
t.Add(model);
}
}
catch (Exception ex)
{
throw ex;
}
return t;
}
此功能用于将提交的表单数据转换为指定的对象列表