双向绑定字典在 MVC 视图中
我的模型中有两个 Dictionary
属性,应该可以正确验证 0 到 5 个项目。例如属性 skill(字符串 dropDownListLabel,字节年)
。
因为我需要支持非 JavaScript 客户端,所以我将所有 5 个输入对渲染到浏览器,仅绑定现有的字典项,一切都很棒。这为新的纯 HTML 表单提供了 5 个空输入对,每个输入对都有唯一的输入名称,这也是我想要的。
这是我使用的序列化(输入名称):
skill[0].Key = "", skill[0].Value = ""
... three more pairs ...
skill[4].Key = "", skill[4].Value = ""
但是在 POST 上,对于既没有指定 Key 也没有指定 Value 的键/值对,DefaultModelBinder 验证错误会在 Value 上产生。
当两者或都不键和值被发布时,我可以使用一种类型和序列化来在DefaultModelBinder中进行验证,所以MVC为我做了尽可能多的工作,仅当它们有内容时将它们添加到集合中?
谢谢, 香农
I have two Dictionary<string, byte>
properties in my model that should validate properly with from 0 to 5 items. For example the property skill (string dropDownListLabel, byte years)
.
Because I need to support non-javascript clients, I render all 5 input pairs to the browser, only binding existing dictionary items, and life is great. This gives 5 empty input pairs for a new plain HTML form, each with unique input names, which I also want.
Here's the serialization (input names) I use:
skill[0].Key = "", skill[0].Value = ""
... three more pairs ...
skill[4].Key = "", skill[4].Value = ""
But on POST, for Key/Value pairs with neither Key nor Value specified, DefaultModelBinder validation errors result on Value.
Is there a type and serialization I can use that will validate in DefaultModelBinder when both or neither Key and Value are POSTed, so MVC does as much work for me as possible, only adding pairs into a collection when they have content?
Thanks,
Shannon
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您无法将空字符串绑定到值类型 (
byte
),因此默认模型绑定器会将您的模型标记为无效。如果您想允许空值,您应该使用可为空的字节:更新:
另一种可能性是使用自定义类型的集合,其中包含两个属性,每个属性分别代表键和值。然后在视图中使用强类型帮助器和编辑器模板,这样您就不必担心有线格式,最后您需要确保键是唯一的,因此您将需要一个自定义验证器。就我个人而言,我在这部分使用 FluentValidation.NET ,但如果您使用数据注释,您将需要一个自定义属性,它将用于装饰视图模型中的集合属性。
You cannot bind an empty string to a value type (
byte
) so the default model binder marks your model as invalid. If you want to allow empty values you should use a nullable byte:UPDATE:
Another possibility is to use a collection of a custom type containing two properties each representing respectively the key and the value. Then use strongly typed helpers and editor templates in your view so that you don't have to worry about the wire format and finally you will need to ensure that the keys are unique so you will need a custom validator. Personally I use FluentValidation.NET for this part but if you are using data annotations you will need a custom attribute which will be used to decorate the collection property in the view model.