仅当值更改时才验证属性?
我想编写一个自定义 ValidationAttribute 来检查给定值是否唯一。
问题在于,在编辑屏幕中,无法保证用户实际更改了值,从而导致错误错误。
有没有办法检查我的属性值是否实际更改?或者我可以仅在值更改时触发该属性吗?
我感觉这个要求可能不属于属性?
I want to write a custom ValidationAttribute that checks if the given value is unique or not.
The problem is that in the edit screen, it is not guaranteed that the user actually changed the value, resulting in a false error.
Is there a way to check in my attribute whether the value actually changed? Or can I trigger the attribute only when the value has changed?
I'm getting the feeling this requirement maybe just doesn't belong in an attribute?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您说 ValidationAttibute 时,您是指使用 DataAnnotations 吗?如果是这样,那么所有这些都适用,否则,对不起,我误解了,这只是本遗嘱的一部分。
我认为你最好的选择是在存储库或 BLL 中使用你的唯一密钥进行记录,至少我是这样做的。获取记录的先前值并查看它们是否更改。如果它们确实发生了变化,则运行您的唯一性检查。
如果您可以将此逻辑放入 ValidationAttribute 中,那么您将拥有更多功能,但我不确定 validationAttribute 是否是最好的东西,因为有很多方法可以绕过它们。根据我对这些属性的理解,您应该仅将它们用作业务逻辑验证的补充,而不是作为验证模型的唯一方法。
请参阅此处有关 DataAnnotations 的更多信息
编辑:
很公平,现在让我们看看我是否可以给出答案来帮助您:)查看此链接,它是用于对任何表中的任何属性进行唯一性检查的代码。相当深入的 LINQ to SQL 内容,但看起来效果很好。您应该能够用它来装饰任何属性,就像使用
或
属性一样。ASP.NET 论坛
When you say ValidationAttibute, do you mean using DataAnnotations? If so, then all of this applies, else, sorry, I misunderstood and only part of this will.
I think your best bet is to do this in the repository or BLL using your unique key for the record, at least this is how I did it. Get the previous values of the record and see if they changed. If they did change, then run your uniqueness checks.
If you can get this logic into the ValidationAttribute, then more power to you, but I am not sure if a validationAttribute would be the best thing since there are ways to get around them. From my understanding of these attributes, you should use them as supplements only to business logic validations and not as the only way that you validate your model.
See here for more info on DataAnnotations
EDIT:
Fair enough, now let's see if I can give an answer to help you :) Check out this link, it is the code for uniqueness checking on any property in any table. Pretty in-depth LINQ to SQL stuff, but looks like it works well. You should be able to decorate any property with this just like using the
<Required>
or<StringLenght>
attributes.ASP.NET Forums