我們知道ASP.NET MVC有個強大的地方就是Form表單提交到action的時候,可以直接將Form的參數(shù)直接裝配到action的參數(shù)實體對象中
比如
action方法 Register(UserModeluserModel)
{
.............................
}
在提交表單的時候,會自動講表單里面的字段封裝到對應(yīng)的UserModel字段里面
那么 WebForm里面可不可以也紫將呢?
因為每次都要去獲得數(shù)據(jù),優(yōu)秀的程序員應(yīng)該要學(xué)會代碼封裝,代碼復(fù)用,重復(fù)的工作不要做
我們其實可以利用反射來實例化對象的(自動裝配)北盟網(wǎng)www.bamn.cn
好了廢話不多....
pageload里面很簡單了
PRotected void Page_Load(object sender, EventArgs e) { if (!IsPost()) { InitPage();//第一次訪問呈現(xiàn)頁面 } else { UserModel userModel = AssembleModel<UserModel>(base.valueCollection); } }
關(guān)鍵就是基類里面的AssembleModel 方法了
基類里面
我們首先獲取到上下文的參數(shù) IT404
protected NameValueCollection valueCollection = HttpContext.Current.Request.Params;
基類很簡單,就是將上下文的提交的參數(shù)存放到valueCollection
然后再看AssembleModel方法了,這是一個泛型方法
/// <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 自動裝配 /// </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)建指定類型實例 foreach (string key in valueCollection.Keys)//所有上下文的值 { foreach (var PropertyInfo in propertyInfoList)//所有實體屬性 { if (key.ToLower() == PropertyInfo.Name.ToLower()) { PropertyInfo.SetValue(obj, valueCollection[key], null);//給對象賦值 } } } return (T)obj; }
很簡單,就是遍歷參數(shù),然后用反射遍歷出實體類的共有屬性,然后根據(jù)名字name來匹配和賦值
所以以后我們只需要一句代碼就能自動裝配上從客戶端存過來的值了
UserModel userModel = AssembleModel<UserModel>(base.valueCollection);好了,感謝你的閱讀,希望對你有幫助了,另外 本博客將會有一些原創(chuàng)的視頻教程分享給大家,感謝大家的支持
新聞熱點
疑難解答