Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Say I use model binding in MVC.
public ActionResult Edit(MyModel model)
{
    db.SaveChanges();
    return View(model);
}

When we pass the model, we miss one field in the model.
What will happen if we save it to db?

What I have tried:

Not sure but I guess
It depends if the field that you forgot to set is mandatory or not.
Posted
Updated 15-Aug-17 9:40am
Comments
Kornfeld Eliyahu Peter 15-Aug-17 6:34am    
What do you mean by 'we miss one field in the model'?
Member 12658724 15-Aug-17 8:31am    
Say we have a class people. It has two properties, name and age. When we pass the instance of people, we only supply the age. We forget to supply the name in the model.
Kornfeld Eliyahu Peter 15-Aug-17 8:38am    
It depends on how it declared in the SQL, if it is NULLABLE it will succeed, otherwise will fail...

1 solution

Based on the code you've posted, it won't do anything at all. There's no code to update the database from the posted data, so the database won't be updated.

You'll need to start by retrieving the corresponding entity from the database:
C#
var entity = db.YourSet.Find(model.PrimaryKey);
if (entity == null) return RedirectToAction("Index");

You'll then need to copy the values from the posted data. You can either do that manually:
entity.Prop1 = model.Prop1;
entity.Prop2 = model.Prop2;
...

Or you can use the TryUpdateModel[^] method. But you'll want to explicitly state which properties can be updated, to prevent a malicious user from overwriting things that shouldn't be changed:
C#
TryUpdateModel(entity, new[] { "Prop1", "Prop2", ... });

Once you've done that, then you can save the changes:
C#
db.SaveChanges();
return View(model);

If you don't copy a property from the posted data, or don't include it in the list of included properties, then the database value will not be changed.

If you copy / include the property, but the user didn't enter a value, then the database value will be cleared. If the property is required, you'll get a validation error when you try to save. Otherwise, the value in the database will be overwritten.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900