.NET MVC通过反射获取数据修
折磨了我一个晚上的问题,奈何对物理的反射印象太深了,整天去想着物理的反射、折射怎么解。感谢少将哥哥给我的指点,经过一个晚上对反射的恶补,最终搞定了。纪念一下。
1.核心代码:
private static void IsUpdate<T>(T old, T current, string id)
{
Model.PerFileHistory history = new Model.PerFileHistory();
Model.Atrributes.ModifyFields atrr = null;
Type type = typeof(T);
PropertyInfo[] propertys = type.GetProperties();
foreach (PropertyInfo property in propertys)
{
if (property.PropertyType.IsValueType || property.PropertyType.Name == "String")
{
if (property.PropertyType.FullName.Contains("Guid"))
continue;
//if (property.Name != "CreateUserID" && property.Name != "CreateTime" && property.Name != "ModifyUserID" && property.Name != "LastModifyTime")//排除这些字段不做判断
//{
if (property.GetCustomAttributes(typeof(Model.Atrributes.ModifyFields), false).Count() > 0)
{
object o1 = property.GetValue(old, null); //以前的值
object o2 = property.GetValue(current, null); //修改后的值
string str1 = o1 == null ? string.Empty : o1.ToString();
string str2 = o2 == null ? string.Empty : o2.ToString();
//判断两者是否相同,不同则插入历史表中
if (str1 != str2)
{
history.BeforeValue = str1; //修改前的值
history.AfterValue = str2; //修改后的值
history.PCardNo = id; //修改数据的ID
history.IPAddress = HanNeng.Common.GetClientIP.GetRealIP(); //获取当前用户的IP地址
atrr = property.GetCustomAttributes(typeof(Model.Atrributes.ModifyFields), false)[0] as Model.Atrributes.ModifyFields;
history.ModifyField = property.Name; //修改的字段名称
history.ModifyFieldName = atrr.FieldsName; //修改的字段中文名称
new BLL.PerFileHistory().AddModel(history);
}
}
//}
}
}
}
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 }
2.获取字段中文名,这个是在Model的类名里设置,示例如下:
/// <summary>
/// 获取字段名称
/// </summary>
public class ModifyFields : Attribute
{
public ModifyFields()
{
}
public ModifyFields(string name)
{
this.FieldsName = name;
}
/// <summary>
/// 修改的字段中文名
/// </summary>
public string FieldsName
{
get;
set;
}
}
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 }
/// <summary>
/// 科部
/// </summary>
[Atrributes.ModifyFields("科部")]
public int? SubjectDep
{
set { _subjectdep = value; }
get { return _subjectdep; }
}
Model类名示例
1 /// <summary>
2 /// 科部
3 /// </summary>
4 [Atrributes.ModifyFields("科部")]
5 public int? SubjectDep
6 {
7 set { _subjectdep = value; }
8 get { return _subjectdep; }
9 }
3.调用方式示例:
if (id != null)
{
Model.PersonFile Person = bllPerson.GetModel<Model.PersonFile>(id);
if (modelPerson != null)
{
Model.Identity identity = Session["Identity"] as Model.Identity;
//if (identity.RoleIDs.ToString() == "R01") //如果是系统管理员,则不记录历史
//{
//对前后数据的不同进行比较
Model.PersonFile OldPerson = Person;
Model.PersonFile NewPerson = modelPerson;
NewPerson.PersonAutoID = OldPerson.PersonAutoID;
IsUpdate(OldPerson, NewPerson, id);
//}
}
}
Controller.CS
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 }
4.最终的效果图:
JQuery结合Ajax实现双击Table表格,使Table变成可编辑,并保存到数据库中
近期在做项目时,要实现通过双击Table表格的TR,使Table行变成可编辑,来实现修改数据并保存到数据库中的功能,无需多说,直接贴代码吧。希望能得到各位同仁指正。
function tdEdit(element, id) {
var i_a = "<input class='edit_td' type='text' style='height:30px; width:40px;' value='";
var i_b = "'/>";
var t_a = "<textarea class='tarea' cols='63' rows='3' style='width:90%'>";
var t_b = "</textarea>";
var td = $(element).find("td");
if (td.length > 0) {
var sc = $(element).children().eq(1).text();
var ss = $(element).children().eq(2).text();
var sequence = $(element).children().eq(3).text();
var weight = $(element).children().eq(4).text();
var max = $(element).children().eq(5).text();
var min = $(element).children().eq(6).text();
var cv = $(element).children().eq(7).text();
var explain = $(element).children().eq(8).text();
$(element).children().eq(1).html($(t_a + sc + t_b));
$(element).children().eq(2).html($(t_a + ss + t_b));
$(element).children().eq(3).html($(i_a + sequence + "'id='num1" + i_b));
$(element).children().eq(4).html($(i_a + weight + "'id='num2" + i_b));
$(element).children().eq(5).html($(i_a + max + "'id='maxvalue" + i_b));
$(element).children().eq(6).html($(i_a + min + "'id='minvalue" + i_b));
$(element).children().eq(7).html($(t_a + cv + t_b));
$(element).children().eq(8).html($(t_a + explain + t_b));
}
$(".edit_td").click(function () {
return false;
});
$(".tarea").click(function () {
return false;
});
//获取焦点
$(".edit_td").trigger("focus");
$(".tarea").trigger("focus");
//文本框失去焦点后提交内容,重新变为文本
$(".save").click(function () {
//验证信息"n":/^\d+$/
var reg = /^[0-9]+\.{0,1}[0-9]{0,2}$/;
var num1 = $("#num1").val();
var num2 = $("#num2").val();
var max = $("#maxvalue").val();
var min = $("#minvalue").val();
if (parseInt(min) > parseInt(max)) {
alert("最小值不能大于最大值!");
return false;
}
if (!reg.test(num1) || !reg.test(num2) || !reg.test(max) || !reg.test(min)) {
alert("请输入数字!");
return false;
}
//重新赋上新值
$(".edit_td").each(function (i) {
var newtxt = $(this).val();
$(element).children().eq(i + 3).html(newtxt);
});
$(".tarea").each(function (j) {
var newtarea = $(this).val();
if (j < 2) {
$(element).children().eq(j + 1).html(newtarea);
}
else {
$(element).children().eq(j + 5).html(newtarea);
}
});
var new_sc = $(element).children().eq(1).text();
var new_ss = $(element).children().eq(2).text();
var new_sequence = $(element).children().eq(3).text();
var new_weight = $(element).children().eq(4).text();
var new_max = $(element).children().eq(5).text();
var new_min = $(element).children().eq(6).text();
var new_cv = $(element).children().eq(7).text();
var new_explain = $(element).children().eq(8).text();
if (new_sc != sc || new_ss != ss || new_sequence != sequence || new_weight != weight || new_max != max || new_min != min || new_cv != cv || new_explain != explain) {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/Ajax/AjaxAction.ashx/UpdateRuleDetail',
data: '{id:"' + id + '",strCon:"' + new_sc + '",strStandard:"' + new_ss + '",Sequence:"' + new_sequence + '",Weight:"' + new_weight + '",CandidateValue:"'
+ new_cv + '",MaxValue:"' + new_max + '",MinValue:"' + new_min + '",Explain:"' + new_explain + '"}',
dataType: 'json',
async: true,
beforeSend: function () {
},
success: function (data) {
alert("保存成功!");
window.location.reload(); //刷新页面
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + ':' + textStatus);
window.location.reload();
}
});
}
else {
alert("温馨提示:您没有做任何修改!");
window.location.reload();
}
});
}
JS
1 function tdEdit(element, id) {
2 var i_a = "<input class='edit_td' type='text' style='height:30px; width:40px;' value='";
3 var i_b = "'/>";
4 var t_a = "<textarea class='tarea' cols='63' rows='3' style='width:90%'>";
5 var t_b = "</textarea>";
6 var td = $(element).find("td");
7 if (td.length > 0) {
8 var sc = $(element).children().eq(1).text();
9 var ss = $(element).children().eq(2).text();
10 var sequence = $(element).children().eq(3).text();
11 var weight = $(element).children().eq(4).text();
12 var max = $(element).children().eq(5).text();
13 var min = $(element).children().eq(6).text();
14 var cv = $(element).children().eq(7).text();
15 var explain = $(element).children().eq(8).text();
16
17 $(element).children().eq(1).html($(t_a + sc + t_b));
18 $(element).children().eq(2).html($(t_a + ss + t_b));
19 $(element).children().eq(3).html($(i_a + sequence + "'id='num1" + i_b));
20 $(element).children().eq(4).html($(i_a + weight + "'id='num2" + i_b));
21 $(element).children().eq(5).html($(i_a + max + "'id='maxvalue" + i_b));
22 $(element).children().eq(6).html($(i_a + min + "'id='minvalue" + i_b));
23 $(element).children().eq(7).html($(t_a + cv + t_b));
24 $(element).children().eq(8).html($(t_a + explain + t_b));
25 }
26 $(".edit_td").click(function () {
27 return false;
28 });
29 $(".tarea").click(function () {
30 return false;
31 });
32 //获取焦点
33 $(".edit_td").trigger("focus");
34 $(".tarea").trigger("focus");
35
36 //文本框失去焦点后提交内容,重新变为文本
37 $(".save").click(function () {
38 //验证信息"n":/^\d+$/
39 var reg = /^[0-9]+\.{0,1}[0-9]{0,2}$/;
40 var num1 = $("#num1").val();
41 var num2 = $("#num2").val();
42 var max = $("#maxvalue").val();
43 var min = $("#minvalue").val();
44 if (parseInt(min) > parseInt(max)) {
45 alert("最小值不能大于最大值!");
46 return false;
47 }
48 if (!reg.test(num1) || !reg.test(num2) || !reg.test(max) || !reg.test(min)) {
49 alert("请输入数字!");
50 return false;
51 }
52 //重新赋上新值
53 $(".edit_td").each(function (i) {
54 var newtxt = $(this).val();
55 $(element).children().eq(i + 3).html(newtxt);
56 });
57 $(".tarea").each(function (j) {
58 var newtarea = $(this).val();
59 if (j < 2) {
60 $(element).children().eq(j + 1).html(newtarea);
61 }
62 else {
63 $(element).children().eq(j + 5).html(newtarea);
64 }
65 });
66
67 var new_sc = $(element).children().eq(1).text();
68 var new_ss = $(element).children().eq(2).text();
69 var new_sequence = $(element).children().eq(3).text();
70 var new_weight = $(element).children().eq(4).text();
71 var new_max = $(element).children().eq(5).text();
72 var new_min = $(element).children().eq(6).text();
73 var new_cv = $(element).children().eq(7).text();
74 var new_explain = $(element).children().eq(8).text();
75 if (new_sc != sc || new_ss != ss || new_sequence != sequence || new_weight != weight || new_max != max || new_min != min || new_cv != cv || new_explain != explain) {
76 $.ajax({
77 type: 'POST',
78 contentType: 'application/json',
79 url: '/Ajax/AjaxAction.ashx/UpdateRuleDetail',
80 data: '{id:"' + id + '",strCon:"' + new_sc + '",strStandard:"' + new_ss + '",Sequence:"' + new_sequence + '",Weight:"' + new_weight + '",CandidateValue:"'
81 + new_cv + '",MaxValue:"' + new_max + '",MinValue:"' + new_min + '",Explain:"' + new_explain + '"}',
82 dataType: 'json',
83 async: true,
84 beforeSend: function () {
85 },
86 success: function (data) {
87 alert("保存成功!");
88 window.location.reload(); //刷新页面
89 },
90 error: function (XMLHttpRequest, textStatus, errorThrown) {
91 alert(XMLHttpRequest + ':' + textStatus);
92 window.location.reload();
93 }
94 });
95 }
96 else {
97 alert("温馨提示:您没有做任何修改!");
98 window.location.reload();
99 }
100
101 });
102 }
前台页面绑定:
<tr ondblclick="tdEdit(this,@item.ID)"></tr>
1 <tr ondblclick="tdEdit(this,@item.ID)"></tr>
最终效果图: