Reputation: 3945
I want to create DateTimeCreated
and DateTimeUpdated
properties in the following model. I want both fields hidden from the user when creating/editing a project on html page. DateTimeCreated
property should be set to current date and time of the user's browser only once (when user creates a project for the first time), similarly DateTimeUpdated
should be set to current date and time of the user's browser every time the user edits/updates the project. Is there a simple way to implement this?
public class Project
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime DateTimeCreated { get; set; }
public DateTime DateTimeUpdated { get; set; }
}
Upvotes: 0
Views: 4052
Reputation: 3106
Just Old Way
private DateTime dateTimeUpdated = default(DateTime);
public DateTime DateTimeUpdated
{
get
{
return (this.dateTimeUpdated== default(DateTime))
? this.dateTimeUpdated= DateTime.Now
: this.dateTimeUpdated;
}
set { this.dateTimeUpdated= value; }
}
Or
public class Project
{
public Project()
{
this.DateTimeUpdated = DateTime.Now;
// This will be update in Init. Or assign as constructor param
// Problem This will update in every init
}
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime DateTimeCreated { get; set; }
public DateTime DateTimeUpdated { get; set; }
}
Upvotes: 2
Reputation: 120
Into the Create function of controller use DateTime.Now
to get current date and time
public ActionResult Create(Project project)
{
SampleDb db=new SampleDb();
// Add audit info
project.DateTimeCreated = DateTime.Now;
project.DateTimeUpdated = DateTime.Now;
//Save entity
db.Projects.Add(project);
db.SaveChanges();
}
Upvotes: 0