开发者

Is it possible to useModel Binding to update an object when not all form values are present?

开发者 https://www.devze.com 2023-03-19 15:11 出处:网络
I am implementing some basic Model Binding to populate an object passed into an Action (normal use). The first Action is a CREATE method, in this case I REQUIRE all parameters be present.

I am implementing some basic Model Binding to populate an object passed into an Action (normal use). The first Action is a CREATE method, in this case I REQUIRE all parameters be present.

For this other Action however it is simply an UPDATE method, in this case I will accept all form values, but I also want it to be possible to only receive ONE or a handful of them and thereby only update the specified fields.

I believe I would have to somehow have them default to null or "" when no value is present. Ho开发者_运维知识库wever, I am under the impression that the Model Bind requires ALL of the parameters be in the POST in order to resolve the Action that takes that object.

Is this possible and I achieve it using the same Model object or will I need to make a 'full version' and a 'partial version'?

EDIT: Trying to make this more clear:

Right now if I have this Action:

public ActionResult MyAction(MyObject obj)

and the MyObject object has 3 variables: var1, var2, and var3

then if I POST to MyAction and only include var1 and var2, it will not resolve because the Model Binding didn't find the var3

However, I want it to work this way! That way if someone wants to ONLY post var1 (along with some ID) I can look up the object in the database and UPDATE var1 of the object while leaving var2 and var3 alone, I am just trying to figure out how to get the Model Binding to resolve properly when form values are missing.


You can use the Bind attribute to whitelist the properties you expect to be posted. This will tell the model binder to only bind the field you specified.

public ActionResult MyAction([Bind(Include = "Field3,Field4")MyObject myObject)

The normal case for an update to a subset of fields is to fetch the MyObject from the database fully filled out and call UpdateModel using the overload with the whitelist of fields to update.

[HttpPost]    
public ActionResult MyAction()
{
    var myObject = GetMyObjectFromDatabase();
    TryUpdateModel(myObject, string.Empty /* prefix */, "Field3,Field4");
    // myObject now has Field3 and Field4 values from the POST
}
0

精彩评论

暂无评论...
验证码 换一张
取 消