If you want to get a list of the fields that have changed between your existing model in your database, and the model that is submitted when modified then you can do this in your Edit Post method of your controller:
IEnumerable<string> changedFields = Audit.GetPropertyDifferences(existingModel, newModel);
I've created a simple function that returns a bunch of strings showing the changed properties:
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;
}
}
This code checks to see if a DisplayName attribute is set in the model, and uses that in place of the property name if it exists.
You can then display these changes or save them to the database like so:
if (changedFields.Count() != 0)
{
foreach (string i in changedFields)
{
// Do something
}
}