我們知道ASP.NET MVC有個(gè)強(qiáng)大的地方就是Form表單提交到action的時(shí)候,可以直接將Form的參數(shù)直接裝配到action的參數(shù)實(shí)體對(duì)象中
比如
action方法 Register(UserModel userModel)
{
.............................
}
在提交表單的時(shí)候,會(huì)自動(dòng)講表單里面的字段封裝到對(duì)應(yīng)的UserModel字段里面
那么 WebForm里面可不可以也紫將呢?
因?yàn)槊看味家カ@得數(shù)據(jù),優(yōu)秀的程序員應(yīng)該要學(xué)會(huì)代碼封裝,代碼復(fù)用,重復(fù)的工作不要做
我們其實(shí)可以利用反射來(lái)實(shí)例化對(duì)象的(自動(dòng)裝配)
好了廢話不多....
pageload里面很簡(jiǎn)單了
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPost())
{
InitPage();//第一次訪問(wèn)呈現(xiàn)頁(yè)面
}
else
{
UserModel userModel = AssembleModel<UserModel>(base.valueCollection);
}
}
關(guān)鍵就是基類里面的AssembleModel 方法了
基類里面
我們首先獲取到上下文的參數(shù) IT404
protected NameValueCollection valueCollection = HttpContext.Current.Request.Params;
基類很簡(jiǎn)單,就是將上下文的提交的參數(shù)存放到valueCollection
然后再看AssembleModel方法了,這是一個(gè)泛型方法
/// <summary>
/// 反射獲取類的屬性
/// </summary>
/// <param name="type"></param>
/// <returns></returns>
protected PropertyInfo[] GetPropertyInfoArray(Type type)
{
PropertyInfo[] props = null;
try
{
object obj = Activator.CreateInstance(type);
props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
}
catch (Exception ex)
{
}
return props;
}
/// <summary>
/// 根據(jù)NameValueCollection 自動(dòng)裝配
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="valueCollection"></param>
/// <returns></returns>
protected T AssembleModel<T>(NameValueCollection valueCollection)
{
PropertyInfo[] propertyInfoList = GetPropertyInfoArray(typeof(T));
object obj = Activator.CreateInstance(typeof(T), null);//創(chuàng)建指定類型實(shí)例
foreach (string key in valueCollection.Keys)//所有上下文的值
{
foreach (var PropertyInfo in propertyInfoList)//所有實(shí)體屬性
{
if (key.ToLower() == PropertyInfo.Name.ToLower())
{
PropertyInfo.SetValue(obj, valueCollection[key], null);//給對(duì)象賦值
}
}
}
return (T)obj;
}
很簡(jiǎn)單,就是遍歷參數(shù),然后用反射遍歷出實(shí)體類的共有屬性,然后根據(jù)名字name來(lái)匹配和賦值
所以以后我們只需要一句代碼 就能自動(dòng)裝配上從客戶端存過(guò)來(lái)的值了
UserModel userModel = AssembleModel<UserModel>(base.valueCollection);