如果您想获取数据库中现有模型与修改时提交的模型之间发生更改的字段列表,则可以在控制器的 Edit Post 方法中执行此操作:
IEnumerable<string> changedFields = Audit.GetPropertyDifferences(existingModel, newModel);
我创建了一个简单的函数,它返回一堆显示更改的属性的字符串:
public static class Audit
{
public static IEnumerable<string> GetPropertyDifferences<T>(this T obj1, T obj2)
{
PropertyInfo[] properties = typeof(T).GetProperties();
List<string> changes = new List<string>();
string name = string.Empty;
foreach (PropertyInfo pi in properties)
{
object value1 = typeof(T).GetProperty(pi.Name).GetValue(obj1, null);
object value2 = typeof(T).GetProperty(pi.Name).GetValue(obj2, null);
DisplayNameAttribute attr = (DisplayNameAttribute)pi.GetCustomAttribute(typeof(DisplayNameAttribute));
if (value1 != value2)
{
if (attr == null)
{
name = pi.Name;
}
else
{
name = attr.DisplayName;
}
if (value1 == null)
{
changes.Add(string.Format("<li>{1} was added to {0}</li>", name, value2));
}
else if (value2 == null)
{
changes.Add(string.Format("<li>{1} was removed from {0}</li>", name, value1));
}
else
{
changes.Add(string.Format("<li>{0} changed from {1} to {2}</li>", name, value1, value2));
}
}
}
return changes;
}
}
此代码检查是否在模型中设置了 DisplayName 属性,如果存在,则使用该属性代替属性名称。
然后您可以显示这些更改或将它们保存到数据库中,如下所示:
if (changedFields.Count() != 0)
{
foreach (string i in changedFields)
{
// Do something
}
}