在一般处理程序中,把Form Post过来的表单集合转换成对象 ,仿 MVC post,反射原理

using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Reflection;
using System.Web;
using WebSite.Models;

namespace testWebuploader.Scripts.Plugin.webuploader_v0._1._2
{
    /// <summary>
    /// webUploader 的摘要说明
    /// </summary>
    public class webUploader : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            HttpFileCollection files = context.Request.Files;
            ImgUploadModel imguploadmodel = FormToClass<ImgUploadModel>(context.Request.Form);
            context.Response.ContentType = "text/plain";
            context.Response.Write("Hello World");
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
        /// <summary>
        /// 把Form Post过来的表单集合转换成对象 ,仿 MVC post
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <returns></returns>
        public T FormToClass<T>(NameValueCollection collection)
        {
            T t = Activator.CreateInstance<T>();
            PropertyInfo[] properties = t.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
            foreach (PropertyInfo _target in properties)
            {
                if (_target.CanWrite)
                {
                    _target.SetValue(t, Convert.ChangeType(collection[_target.Name], _target.PropertyType));
                }
            }
            return t;
        }
    }
}

 

posted on 2014-05-17 11:33  shanheblog  阅读(1732)  评论(2编辑  收藏  举报

导航