Saturday, 14 September 2013

Elegant way to update model

Elegant way to update model

Lets say I have a model with more then 20 properties.
Some of them can be edited in a view by the user, however for security
reasons data like passwords are not kept in hidden fields, so when I post
view model to controller some properties are nulls
How to check which properties changed without writing too much code?
bad idea:
[HttpPost]
public ActionResult Edit(BigModel model)
{
BigModel old=db.Get(new.id);
if(model.Property1 !=null && old.Property1 != model.Property1)
old.Property1=model.Property1
if(model.Property1 !=null && old.Property1 != model.Property1)
old.Property1=model.Property1
if(model.Property1 !=null && old.Property1 != model.Property1)
old.Property1=model.Property1
...
if(model.Property1 !=null && old.Property20 != model.Property20)
old.Property20=model.Property20
}

No comments:

Post a Comment