Reputation: 784
I'm creating an MVC 5.2 and cannot seem to get the DateTime field to be readonly and not get updated after an Edit. I insert a row and the date is set to the current datetime. Then when I edit the row in the MVC view the datetime becomes 1/1/0001 12:00:00 AM. What do I need to do to get the datetime to display but not update when I edit the row?
[Table("Employee")]
public partial class Employee
{
[Key]
public int TestID { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[ReadOnly(true)]
[Column(TypeName = "datetime2")]
public DateTime LastUpdated { get; set; }
}
CREATE TABLE [dbo].[Employee] (
[TestID] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[LastUpdated] DATETIME2 (7) DEFAULT (getdate()) NOT NULL,
PRIMARY KEY CLUSTERED ([TestID] ASC));
Upvotes: 0
Views: 1054
Reputation: 21211
Even if you don't plan on changing the value in the database, if you want the value to persist across a POST request you need to bind it to an input:
@Html.HiddenFor(m => m.LastUpdated)
Hopefully, you're not using your EF objects in your views, but even then, you can control what gets updated:
var emp = context.Employess.SingleOrDefault(e => e.TestID == model.TestID);
if(emp != null)
{
emp.Name = model.Name;
context.SaveChanges();
}
Assuming, of course, that context
is an instance of your EF DbContext and model
is the name of the parameter:
public ActionResult Edit(Employee model)
{
/* ... */
}
Upvotes: 1