按模型获取前台提交数据(反射)

 

效果图:

视图代码:

<form action="form.aspx" method="post">
    <input type="text" name="card" /><p />
    <input type="text" name="pwd" /><p />
    <input type="text" name="status" /><p />
    <input type="submit" value="input" />
</form>
View Code

功能代码:

        protected void Page_Load(object sender, EventArgs e)
        {
            admin a = new admin();
            GetFormToM<admin>(ref a, Request.Form); //获取表单的值
            OutT<admin>(a);                         //输出表单的值
        }
        private class admin
        {
            public string card { set; get; }
            public string pwd { set; get; }
            public int status { set; get; }
        }  //模型
        static void GetFormToM<T>(ref T m,NameValueCollection form)
        {
            Type t = m.GetType();
            PropertyInfo[] pi = t.GetProperties();
            foreach(PropertyInfo p in pi)
            {
                if(form[p.Name] != null )
                {
                    p.SetValue(m, Convert.ChangeType(form[p.Name], p.PropertyType), null);
                }
            }
        } //获得表单
        static void OutT<T>(T m)
        {
            Type t = m.GetType();
            PropertyInfo[] pi = t.GetProperties();
            foreach(var p in pi)
            {
                HttpContext.Current.Response.Write(p.Name + " = " + p.GetValue(m)+"<p/>");
            }
        }  //输出模型
View Code

 

posted @ 2016-01-06 23:58  少时不知贵  阅读(292)  评论(0编辑  收藏  举报