ASP.NET WebForm Form表單如何實現MVC那種“自動裝配”效果呢?

我們知道ASP.NET MVC有個強大的地方就是Form表單提交到action的時候,可以直接將Form的參數直接裝配到action的參數實體對象中

比如

action方法 Register(UserModel userModel)

{

   ............................. 

}

在提交表單的時候,會自動講表單裏面的字段封裝到對應的UserModel字段裏面

那麼 WebForm裏面可不可以也紫將呢?

因爲每次都要去獲得數據,優秀的程序員應該要學會代碼封裝,代碼複用,重複的工作不要做

我們其實可以利用反射來實例化對象的(自動裝配)北盟網www.bamn.cn

好了廢話不多....

pageload裏面很簡單了

protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPost())
            {
                InitPage();//第一次訪問呈現頁面
            }
            else
            {
                UserModel userModel = AssembleModel<UserModel>(base.valueCollection);
            }
        }

關鍵就是基類裏面的AssembleModel 方法了

基類裏面

我們首先獲取到上下文的參數 IT404


protected NameValueCollection valueCollection = HttpContext.Current.Request.Params;

基類很簡單,就是將上下文的提交的參數存放到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>
        /// 根據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);//創建指定類型實例
            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;
        }



很簡單,就是遍歷參數,然後用反射遍歷出實體類的共有屬性,然後根據名字name來匹配和賦值

所以以後我們只需要一句代碼 就能自動裝配上從客戶端存過來的值了

UserModel userModel = AssembleModel<UserModel>(base.valueCollection);

發佈了88 篇原創文章 · 獲贊 16 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章