当并非所有表单值都存在时,是否可以使用模型绑定来更新对象?
我正在实现一些基本的模型绑定来填充传递到操作中的对象(正常使用)。第一个 Action 是 CREATE 方法,在本例中我要求所有参数都存在。
然而,对于另一个 Action,它只是一个 UPDATE 方法,在这种情况下,我将接受所有表单值,但我也希望它可以只接收一个或其中的几个值,从而只更新指定的字段。
我相信当没有值存在时,我必须以某种方式将它们默认为 null 或“”。但是,我的印象是模型绑定要求所有参数都在 POST 中才能解析采用该对象的操作。
这是否可能,并且我使用相同的模型对象来实现它,或者我需要制作“完整版本”和“部分版本”?
编辑:试图让这一点更清楚:
现在如果我有这个操作:
公共 ActionResult MyAction(MyObject obj)
并且 MyObject 对象有 3 个变量:var1、var2 和 var3
那么如果我 POST 到 MyAction 并且只包含 var1 和 var2,它将无法解析,因为模型绑定没有找到 var3
但是,我希望它能这样工作!这样,如果有人只想发布 var1 (以及一些 ID),我可以在数据库中查找对象并更新对象的 var1,同时保留 var2 和 var3,我只是想弄清楚如何获取模型绑定当表单值丢失时正确解决。
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. However, 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用
Bind
属性将您希望发布的属性列入白名单。这将告诉模型绑定器仅绑定您指定的字段。更新字段子集的正常情况是从完全填写的数据库中获取 MyObject,并使用要更新的字段白名单的重载来调用 UpdateModel。
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.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.