//以前寫法
DLC_category d = new DLC_category();
d.sex = Request["sex"];
d.id = Convert.ToInt32(Request["id"]);
//現(xiàn)在寫法
var category = RequestToModel.GetSingleFormDLC_category>();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace SyntacticSugar
{
/// summary>
/// ** 描述:表單幫助類
/// ** 創(chuàng)始時(shí)間:2015-4-17
/// ** 修改時(shí)間:-
/// ** 作者:sunkaixuan
/// ** qq:610262374 歡迎交流,共同提高 ,命名語(yǔ)法等寫的不好的地方歡迎大家的給出寶貴建議
/// /summary>
public class RequestToModel
{
/// summary>
/// 提交表單通過反射獲取單個(gè)像
/// 注意:表單控件name必包含對(duì)應(yīng)類中的第一個(gè)字段,否則將報(bào)錯(cuò)
/// /summary>
public static T GetSingleFormT>() where T : new()
{
T t = SetListT>(null, 0).Single();
return t;
}
/// summary>
/// 提交表單通過反射獲取單個(gè)像
/// 注意:表單控件name必包含對(duì)應(yīng)類中的第一個(gè)字段,否則將報(bào)錯(cuò)
/// param name="appstr">控件前綴,比如 name="form1.sex" appstr可以設(shè)為form1/param>
/// /summary>
public static T GetSingleFormT>(string appstr) where T : new()
{
T t = SetListT>(appstr, 0).Single();
return t;
}
/// summary>
/// 提交表單通過反射獲取多個(gè)對(duì)像
/// 注意:表單控件name必包含對(duì)應(yīng)類中的第一個(gè)字段,否則將報(bào)錯(cuò)
/// /summary>
/// typeparam name="type">/typeparam>
/// param name="type">/param>
/// returns>/returns>
public static ListT> GetListByFormT>() where T : new()
{
ListT> t = SetListT>(null, 0);
return t;
}
/// summary>
/// 提交表單通過反射獲取多個(gè)對(duì)像
/// 注意:表單控件name必包含對(duì)應(yīng)類中的第一個(gè)字段,否則將報(bào)錯(cuò)
/// /summary>
/// typeparam name="type">/typeparam>
/// param name="appstr">控件前綴,比如 name="form1.sex" appstr可以設(shè)為form1/param>
/// returns>/returns>
public static ListT> GetListByFormT>(string appstr) where T : new()
{
ListT> t = SetListT>(appstr, 0);
return t;
}
/// summary>
/// 提交表單通過反射獲取多個(gè)對(duì)像
/// /summary>
/// typeparam name="type">/typeparam>
/// param name="appstr">控件前綴,比如 name="form1.sex" appstr可以設(shè)為form1/param>
/// typeparam name="index">表單控件中第一個(gè)控件,對(duì)應(yīng)類中字段在該類中的索引號(hào),特殊情況可以是第二第三控件/typeparam>
/// returns>/returns>
private static ListT> GetListByFormT>(string appstr, int index) where T : new()
{
ListT> t = SetListT>(appstr, index);
return t;
}
private static ListT> SetListT>(string appendstr, int index) where T : new()
{
ListT> t = new ListT>();
try
{
var properties = new T().GetType().GetProperties();
var subNum = System.Web.HttpContext.Current.Request[appendstr + properties[index].Name].Split(',').Length;
for (int i = 0; i subNum; i++)
{
var r = properties;
var model = new T();
foreach (var p in properties)
{
string pval = System.Web.HttpContext.Current.Request[appendstr + p.Name + ""];
if (!string.IsNullOrEmpty(pval))
{
pval = pval.Split(',')[i];
string pptypeName = p.PropertyType.Name;
p.SetValue(model, Convert.ChangeType(pval, p.PropertyType), null);
}
}
t.Add(model);
}
}
catch (Exception ex)
{
throw ex;
}
return t;
}
}
}