利用反射,泛型,靜態方法快速擷取表單值到Model

來源:互聯網
上載者:User
轉自:http://www.cnblogs.com/henq/archive/2009/08/31/1557726.html

在項目中經常需要處理表單,給model賦值,很煩人的一些重複代碼。如下邊的代碼:Code
            News news = new News();
            news.Id = int.Parse(Request.Form["Id"]);
            news.Category = int.Parse(Request.Form["Category"]);
            news.Title = Request.Form["Title"];
            
            news.CreateTime = DateTime.Parse(Request.Form["CreateTime"]);

經常還會出現寫錯情況,尤其是加班寫這種無聊代碼的時候...
使用反射,泛型,靜態方法可以很容易解決這個問題。說的好像有點高深,其實超級簡單。見代碼。Code
public static class HenqPost<T> where T: new()
    {
        /**//// <summary>
        /// 為Model賦值
        /// </summary>
        /// <typeparam name="T">Model</typeparam>
        /// <param name="t">model</param>
        /// <param name="form">Request</param>
        /// <returns></returns>
        public static int GetPost<T>(ref T t, NameValueCollection form)
        {
            int va=0;
            Type type = t.GetType();//擷取類型
            PropertyInfo[] pi=type.GetProperties();//擷取屬性集合
            foreach( PropertyInfo p in pi )
            {
                if (form[p.Name] != null)
                {
                    try
                    {
                        p.SetValue(t, Convert.ChangeType(form[p.Name], p.PropertyType), null);//為屬性賦值,並轉換索引值的類型為該屬性的類型
                        va++;//記錄賦值成功的屬性數
                    }
                    catch
                    {                        
                    }
                }
            }
            return va;
        }
    }

之所以用靜態方法,主要是圖方便,不用new。
以後所有的表單都可以很簡單的處理了,兩行代碼搞定。            News news = new News();
            HenqPost<News>.GetPost(ref news, Request.Form);
            //煩人的為實體類賦值就Over了。

不需要任何配置,約定是最好的配置。
約定:表單項的名稱最好和實體類的屬性名稱字對應(如果你要不一樣,反射方法根據自己的規則改造下)。
為表單賦值,如果是webform的話也可以採取這種方式,可以自己寫下,原理差不多。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.