I managed to create the basic CRUD operations using asp.net MVC
But I had a problem with regards to my field Status
, CreatedOn
and CreatedBy
.
I want these fields to be populated during the Create Action and is not updated during the Edit Action but I don't want to use @HiddenFor for these fields because you can edit the DOM and still update these information before a POST request.
So basically what I want is to Patch Update my model with whatever data sent in the POST request. So I don't have to worry about the fields I don't want being modified are being changed in the Edit Action.
Here is my code for the model and action.
Model
[Table("Account")]
public class Account
{
#region Properties
[Key]
public int AccountID { get; set; }
[Required]
[StringLength(50)]
[DisplayName("Account Name")]
public string Name { get; set; }
[Required]
[DisplayName("Time Offset")]
[Range(-24,24)]
public decimal TimeOffset { get; set; }
[StringLength(20)]
[DisplayName("Status")]
public string Status { get; set; }
public DateTime CreatedOn { get; set; }
public int CreatedBy { get; set; }
public DateTime? ModifiedOn { get; set; }
public int ModifiedBy { get; set; }
#endregion
}
public class DbAccount : DbContext
{
public DbSet<Account> Accounts { get; set; }
}
Controller Action for Create
[HttpPost]
public ActionResult Create(Account account)
{
if (ModelState.IsValid)
{
account.Status = "ENABLED";
account.CreatedOn = DateTime.Now;
account.CreatedBy = 1;
db.Accounts.Add(account);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(account);
}
Controller Action for Edit
[HttpPost]
public ActionResult Edit(Account account)
{
if (ModelState.IsValid)
{
account.ModifiedOn = DateTime.Now;
account.ModifiedBy = 1;
db.Entry(account).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(account);
}
How can I modify the model without affecting some specific properties specifically CreatedOn
and CreatedBy
, I want these properties to preserve their original value during Edit Action. I don't want to use Hidden Fields to store them. With my existing solution I used Hidden Fields but it can be modified in the DOM before POST request so it's not secure.