Click here to Skip to main content
14,209,042 members
Rate this:
Please Sign up or sign in to vote.
Say I use model binding in MVC.
public ActionResult Edit(MyModel model)
    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.
Updated 15-Aug-17 9:40am
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

Rate this:
Please Sign up or sign in to vote.

Solution 1

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:
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:
TryUpdateModel(entity, new[] { "Prop1", "Prop2", ... });

Once you've done that, then you can save the changes:
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.

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

Advertise | Privacy | Cookies | Terms of Service
Web06 | 2.8.190617.2 | Last Updated 15 Aug 2017
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100