Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC4 edit method changes values to null if correspndong fields don't exist in the form

My table has two columns CreatedBy and CreateTime. In my view form, I don't have these fields. Now when I update a record using ASP.NET MVC4 Edit (post) method, these columns are set to null. But I want to retain the values. I know in my Edit (post) method, I can retrieve the record from the database and set these manually. But I am wondering whether I can ask Entity Framework not to change the values of these fields.

like image 784
N Rocking Avatar asked Aug 13 '13 19:08

N Rocking


2 Answers

No you can't, if you want to keep the old values then you have to get the record first and then manually assign the values that you want to update. The only other way is to go through your entity property by property and tag which ones you want to modify, like so:

db.MyEntity.Attach(myEntity);
db.Entry(myEntity).Property(e => e.MyProperty).IsModified = true;
db.SaveChanges();

either way you end up having to do the manual work yourself.

like image 147
SOfanatic Avatar answered Sep 20 '22 19:09

SOfanatic


You have to choices here:

1) As @KennyZ mentioned, add to @Html.HiddenFor() somewhere in your view, into your form:

@Html.HiddenFor(m => m.CreatedBy)
@Html.HiddenFor(m => m.createTime) 

2) You can manually update that entity and leave those two properties alone:

var ent = dbctx.Entities.Find(model.ID);

ent.Prop1 = model.Prop1;
// ... also for other properties except those two property

dbctx.SaveChanges();
like image 36
Amin Saqi Avatar answered Sep 18 '22 19:09

Amin Saqi