.NET MVC通過反射獲取數據修改歷史記錄,並插入數據表中,.netmvc
折磨了我一個晚上的問題,奈何對物理的反射印象太深了,整天去想著物理的反射、折射怎麼解。感謝少將哥哥給我的指點,經過一個晚上對反射的惡補,最終搞定了。紀念一下。
1.核心代碼:

![]()
1 private static void IsUpdate<T>(T old, T current, string id)
2 {
3 Model.PerFileHistory history = new Model.PerFileHistory();
4 Model.Atrributes.ModifyFields atrr = null;
5 Type type = typeof(T);
6 PropertyInfo[] propertys = type.GetProperties();
7 foreach (PropertyInfo property in propertys)
8 {
9 if (property.PropertyType.IsValueType || property.PropertyType.Name == "String")
10 {
11 if (property.PropertyType.FullName.Contains("Guid"))
12 continue;
13 //if (property.Name != "CreateUserID" && property.Name != "CreateTime" && property.Name != "ModifyUserID" && property.Name != "LastModifyTime")//排除這些字段不做判斷
14 //{
15 if (property.GetCustomAttributes(typeof(Model.Atrributes.ModifyFields), false).Count() > 0)
16 {
17 object o1 = property.GetValue(old, null); //以前的值
18 object o2 = property.GetValue(current, null); //修改後的值
19 string str1 = o1 == null ? string.Empty : o1.ToString();
20 string str2 = o2 == null ? string.Empty : o2.ToString();
21 //判斷兩者是否相同,不同則插入歷史表中
22 if (str1 != str2)
23 {
24 history.BeforeValue = str1; //修改前的值
25 history.AfterValue = str2; //修改後的值
26 history.PCardNo = id; //修改數據的ID
27 history.IPAddress = HanNeng.Common.GetClientIP.GetRealIP(); //獲取當前用戶的IP地址
28 atrr = property.GetCustomAttributes(typeof(Model.Atrributes.ModifyFields), false)[0] as Model.Atrributes.ModifyFields;
29 history.ModifyField = property.Name; //修改的字段名稱
30 history.ModifyFieldName = atrr.FieldsName; //修改的字段中文名稱
31
32 new BLL.PerFileHistory().AddModel(history);
33 }
34 }
35 //}
36 }
37 }
38 }
View Code
2.獲取字段中文名,這個是在Model的類名裡設置,示例如下:

![]()
1 /// <summary>
2 /// 獲取字段名稱
3 /// </summary>
4 public class ModifyFields : Attribute
5 {
6 public ModifyFields()
7 {
8 }
9 public ModifyFields(string name)
10 {
11 this.FieldsName = name;
12 }
13 /// <summary>
14 /// 修改的字段中文名
15 /// </summary>
16 public string FieldsName
17 {
18 get;
19 set;
20 }
21 }
Model

![]()
1 /// <summary>
2 /// 科部
3 /// </summary>
4 [Atrributes.ModifyFields("科部")]
5 public int? SubjectDep
6 {
7 set { _subjectdep = value; }
8 get { return _subjectdep; }
9 }
Model類名示例
3.調用方式示例:

![]()
1 if (id != null)
2 {
3 Model.PersonFile Person = bllPerson.GetModel<Model.PersonFile>(id);
4 if (modelPerson != null)
5 {
6 Model.Identity identity = Session["Identity"] as Model.Identity;
7 //if (identity.RoleIDs.ToString() == "R01") //如果是系統管理員,則不記錄歷史
8 //{
9 //對前後數據的不同進行比較
10 Model.PersonFile OldPerson = Person;
11 Model.PersonFile NewPerson = modelPerson;
12 NewPerson.PersonAutoID = OldPerson.PersonAutoID;
13 IsUpdate(OldPerson, NewPerson, id);
14 //}
15 }
16 }
Controller.CS
4.最終的效果圖:

用JAVA的MVC模式怎向數據庫插入更改數據?
插入:
在jsp頁面中寫一個form表單,包括學號,姓名兩個文本框,和一個提交按鈕
輸入學號和姓名後,form表單把值傳給servlet,servlet負責創建javabean對象,並把form傳過來的值交給javabean做數據庫處理
javabean主要負責連接數據庫,然後插入數據
修改:
比插入多一個讀數據的過程,jsp先通過創建javabean對象,然後把想修改的數據讀出來,顯示到學號,和姓名文本框內,其他的步驟和插入一樣
aspnet mvc:怎從數據庫中查詢數據,並顯示在頁面的數據表格中(舉出一個具體一些的例子)
說清楚一點吧~