反射实现所有实体的增删改操作(jQuery+json)
发布时间:2020-12-16 19:28:59 所属栏目:百科 来源:网络整理
导读:续前面的无刷新分页控件,编辑,修改控件的实现, (这里是地址:http://www.cnblogs.com/liuju150/archive/2009/09/11/1564994.html) 那么,有三四十张表的话, 前台表单是自动生成的. 只不过生成的实体和数据库里的表名都是有规律可以找的. 还有操作实体的类, 所
续前面的无刷新分页控件,编辑,修改控件的实现, (这里是地址:http://www.cnblogs.com/liuju150/archive/2009/09/11/1564994.html) 那么,有三四十张表的话, 前台表单是自动生成的. 只不过生成的实体和数据库里的表名都是有规律可以找的. 还有操作实体的类, 所以我只要通过前台把表单传过来. 我就可以知道要反射到哪个实体, 然后对实体进行相应的赋值. 再反射一个实体操作的类. 就可以实现对实体的增删改操作了
上面是我的数据库表名 下面是我的实体,和实体操作的类名
private void InsertAndUpdateObj(HttpContext context) { string ClassName = context.Request.Form["ClassName"].ToString(); string ClassData = context.Request.Form["ClassData"].ToString(); string IntOrUpd = context.Request.Form["isIns"].ToString(); string[] ClassNameArray = ClassName.Split('_'); string CNStr = ""; for (int i = 0; i < ClassNameArray.Length; i++) { CNStr += ClassNameArray[i].Substring(0,1).ToUpper() + ClassNameArray[i].Substring(1).ToLower(); } ClassName = CNStr; //反射实体 Assembly Ab = Assembly.Load("GradView.Library"); Type type = Ab.GetType("GradView.Library.Data." + ClassName,true,false); object obj = Activator.CreateInstance(type); DataContractJsonSerializer dcjs = new DataContractJsonSerializer(type); MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(ClassData)); obj = dcjs.ReadObject(ms); //反射业务操作 string opName = "Biz" + ClassName; string opMethod = "Insert"; switch (IntOrUpd) { case "0": opMethod = "Update"; break; case "1": opMethod = "Insert"; break; case "2": opMethod = "Delete"; break; default: opMethod = "Insert"; break; } Type opType = Ab.GetType("GradView.Library.Data." + opName,false); object opObj = Activator.CreateInstance(opType); MethodInfo[] mi = opType.GetMethods(); for (int i = 0; i < mi.Length; i++) { if (mi[i].Name == opMethod) { object[] par = { obj }; try { mi[i].Invoke(opObj,par); break; } catch { } } } }
所以我只要写这样的方法来实现, 前台就可以通过jQuery把表单里的值组成json 后台接收这个json 就可以对实体进行相应的操作了 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |