I have a model which has a DateTime property which stores the date in which the object is created.
public class UserProfile
{
public int Id { get; set; }
public string Name { get; set; }
[Required]
[DataType(DataType.Date)]
public DateTime DateCreated { get; set; }
}
When a User Profile is created, the DateCreated is set in the create method like this :
profile.DateCreated = DateTime.Now.Date;
But in my edit method, I don't want this DateCreated value to be changed so I removed it from the Include attribute.
Even so, a DateTime value of 01/01/0001 is being passed to the model, even though I don't want that field being updated. This is what is causing the SqlException but I dont know how to stop it.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "Id,Name")] UserProfile profile)
{
if (ModelState.IsValid)
{
db.Entry(profile).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(profile);
}
I tried removing the [Required] attribute but still not resolved.
I made DateCreated nullable by adding a ? in front of DateTime
public DateTime? DateCreated { get; set; }
But that caused the DateCreated to become null when ever I edited the UserProfile.