利用反射实现 MVC中的 数据插入

来源:互联网 发布:ps色环插件 for mac 编辑:程序博客网 时间:2024/05/24 03:09

最近在学研究反射,感觉功能很强大,闲着没事就写了个小Demo.希望到时候能实现所有页面根据模型生产,所有增删改集成到控制器的一个方法中。

 

界面如下:很简单的一个Form表单,点击按钮后提交到服务器

页面Html代码:

    <form class="form-horizontal" method="post" action="/Home/Check">        <div class="control-group row col-lg-12 col-lg-offset-5 ">            <div class="controls">                <input type="text" id="UserID" name="UserID" placeholder="用户ID">            </div>        </div>        <div class="control-group col-lg-12 col-lg-offset-5">            <div class="controls">                <button type="submit" class="btn-primary">签到</button>            </div>        </div>    </form>

 

服务器端代码:

 //签到        [HttpPost]        [LoginFilter]        public string Check()        {            //方式1:直接根据提交的 ’表单键值对‘ 生成Sql语句 实现增加            ReflectionHelper.InsertSql("T_CheckRecords", "CollectInformation.Models", ReflectionHelper.GetFormInfo("T_CheckRecords", "CollectInformation.Models"));            //方式2:根据提交的 ’表单键值对‘ 生成对象,再根据对象生成Sql语句  实现增加            object obj = ReflectionHelper.GetFormObject("T_CheckRecords", "CollectInformation.Models");            ReflectionHelper.InsertSql(obj);            //方式3:根据提交的 ’表单键值对‘ 生成对象,再调用MVC自带的方法,可实现增删改            db.Entry(obj).State = EntityState.Added;//EntityState.Deleted   EntityState.Modified   EntityState.Added            db.SaveChanges();            return "";          }

 

运行结果:

 

 

这样就实现了MVC的插入功能了。结合上次的文章http://blog.csdn.net/xyj2014/article/details/49454701,可以实现自动生成页面,统一处理数据库添加请求

 

最后贴下自己写的反射帮助类,有不足之处希望博友们指出

 

using System;using System.Collections.Generic;using System.Linq;using System.Reflection;using System.Web;using System.Web.Mvc;namespace Panda.Lib{    public static class ReflectionHelper    {        #region 取到对象的属性集合              public static string[] GetProperties(string FullobjName)        {            var p = Assembly.GetExecutingAssembly().CreateInstance(FullobjName).GetType().GetProperties();            string[] result = new string[p.Length];            for (int i = 0; i < p.Length; i++)            {                result[i] = p[i].Name;            }            return result;        }        public static string[] GetProperties(string objName, string nameSpace)        {            return GetProperties(nameSpace + "." + objName);        }        #endregion        #region 获取Form表单中提交的键值对        public static string[][] GetFormInfo(string FullobjName)        {            //根据名称获取属性            string[] Properties = GetProperties(FullobjName);            //存储属性值            string[] Values = new string[Properties.Length];            for (int i = 0; i < Properties.Length; i++)            {                Values[i] = (HttpContext.Current.Request.Form[Properties[i]] == null) ? "-1" : HttpContext.Current.Request.Form[Properties[i]];            }            string[][] result = new string[][] { Properties, Values };            return result;        }        public static string[][] GetFormInfo(string objName, string nameSpace)        {            return GetFormInfo(nameSpace + "." + objName);          }        #endregion        #region 根据键值对转化为的对象  (实例化对象并给对象赋值)        public static object GetFormObject(string FullobjName)        {            //实例化对象            object obj = Assembly.GetExecutingAssembly().CreateInstance(FullobjName);            //获取对象属性集合            string[] Properties = GetProperties(FullobjName);            //获取对象值数组            string[] Values = GetFormInfo(FullobjName)[1];            //给对象的属性挨个赋值            for (int i = 0; i < Properties.Length; i++)            {                var Property = obj.GetType().GetProperty(Properties[i]);                //判断属性类型                if (Property.PropertyType.Name.Contains("Int"))                {                    Property.SetValue(obj, int.Parse(Values[i]));                }                else if (Property.PropertyType.Name.Contains("Float"))                {                    Property.SetValue(obj, float.Parse(Values[i]));                }                else                {                    Property.SetValue(obj, Values[i]);                }                                          }            return obj;        }        public static object GetFormObject(string objName, string nameSpace)        {            return GetFormObject(nameSpace + "." + objName);        }        #endregion        #region 获取对象的属性键值对        public static string[][] GetObjInfo(object obj)        {            var t = obj.GetType();            var p = t.GetProperties();            string[] Properties = new string[p.Length];            string[] Values = new string[p.Length];            for (int i = 0; i < p.Length; i++)            {                Properties[i] = p[i].Name;                var temp = t.GetProperty(p[i].Name).GetValue(obj);                Values[i] = temp == null ? "未填写" : temp.ToString();            }            string[][] result = new string[][] { Properties, Values };            return result;        }        #endregion        #region 根据对象的‘属性键值对’或‘已赋值对象’生成Sql语句  [规定表名和类名必须相同]        public static string InsertSql(string objName, string nameSpace,string[][] Data)        {                                   //表名,默认等于类名            string tableName = objName;            string colNames = "";//列名字符串            string colValues = "";//列名字符串            for (int i = 0; i < Data[0].Length; i++)            {                colNames += Data[0][i];                colValues += "'" + Data[1][i] + "'";                colNames += ",";                colValues += ",";            }            char tttt = colNames[colNames.Length - 1];            if (colNames[colNames.Length - 1] == ',')            {                colNames = colNames.Substring(0, colNames.Length - 1);                colValues = colValues.Substring(0, colValues.Length - 1);            }            string sql = "insert into " + tableName + "(" + colNames + ")values(" + colValues + ")";            return sql;        }        public static string InsertSql(object Data)        {            Type type = Data.GetType();            string tableName = type.Name;//表名            PropertyInfo[] Properties = type.GetProperties();            string colNames = "";//列名字符串            string colValues = "";//列名字符串            for (int i = 0; i < Properties.Length; i++)            {                //过滤外键                if (Properties[i].PropertyType.Name.Contains("String") || Properties[i].PropertyType.Name.Contains("Int") || Properties[i].PropertyType.Name.Contains("Float"))                {                    colNames += Properties[i].Name;                    colValues += "'" + Properties[i].GetValue(Data) + "'";                    colNames += ",";                    colValues += ",";                }            }            char tttt = colNames[colNames.Length - 1];            if (colNames[colNames.Length - 1] == ',')            {                colNames = colNames.Substring(0, colNames.Length - 1);                colValues = colValues.Substring(0, colValues.Length - 1);            }            string sql = "insert into " + tableName + "(" + colNames + ")values(" + colValues + ")";            return sql;        }        #endregion    }}


 

 

1 0
原创粉丝点击