如何进行 Web 表单模型验证?
我们有一个具有三层的应用程序:UI、业务和数据。数据层包含实体框架 v4 并自动生成我们的实体对象。我已经为实体 VendorInfo
创建了一个伙伴类:
namespace Company.DataAccess
{
[MetadataType(typeof(VendorInfoMetadata))]
public partial class VendorInfo
{
}
public class VendorInfoMetadata
{
[Required]
public string Title;
[Required]
public string Link;
[Required]
public string LinkText;
[Required]
public string Description;
}
}
我希望此验证冒泡到 UI,包括分配给它们的自定义验证消息。在 MVC 中这是小菜一碟,但在 Web 表单中我不知道从哪里开始。在 ASP.NET Web 表单中利用模型验证的最佳方法是什么?
我确实找到了一篇文章,解释了如何为它构建一个服务器控件,但我似乎无法让它工作。它编译甚至识别该控件,但我永远无法让它启动。
有什么想法吗?
谢谢大家。
We have an application with three layers: UI, Business, and Data. The data layer houses Entity Framework v4 and auto-generates our entity objects. I have created a buddy class for the entity VendorInfo
:
namespace Company.DataAccess
{
[MetadataType(typeof(VendorInfoMetadata))]
public partial class VendorInfo
{
}
public class VendorInfoMetadata
{
[Required]
public string Title;
[Required]
public string Link;
[Required]
public string LinkText;
[Required]
public string Description;
}
}
I want this validation to bubble up to the UI, including custom validation messages assigned to them. In MVC this is a piece of cake but in web forms I have no clue where to begin. What is the best way to utilize model validation in asp.net web forms?
I did find an article that explains how to build a server control for it, but I can't seem to get it working. It compiles and even recognizes the control but I can never get it to fire.
Any ideas?
Thanks everyone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我解决了。看起来我找到的服务器控件未设计为通过 MetadataType 属性读取伙伴类中的字段。我修改了代码以在伙伴类而不是实体类本身中查找其验证属性。
下面是链接服务器控件的修改版本:
此代码仅在伙伴类中查找。如果您希望它检查实际的类,然后检查其伙伴类,则必须相应地修改它。我没有费心这样做,因为通常如果您使用伙伴类来验证属性,那是因为您无法使用主实体类(例如实体框架)中的属性。
I solved it. It would appear that the server control I found was not designed to read fields in a buddy class via the MetadataType attribute. I modified the code to look for its validation attributes in the buddy class rather than the entity class itself.
Here is the modified version of the linked server control:
This code only looks in the buddy class. If you want it to check an actual class and then its buddy class, you'll have to modify it accordingly. I did not bother doing that because usually if you are using a buddy class for validation attributes it's because you are not able to use the attributes in the main entity class (e.g. Entity Framework).
对于 Web 表单中的模型验证,我使用 DAValidation 库。它支持客户端验证(包括非侵入式验证),以及基于与 MVC 相同原理的可扩展性。它已获得 MS-PL 许可,可通过 Nuget 获取。
这是有点过时的文章描述思想控制是如何建立的。
For model validation in web forms I'm using DAValidation library. It supports validation on client side (including unobtrusive validation), extensibility based on same principles as in MVC. It is MS-PL licensed and available via Nuget.
And here is bit out of date article describing with what thoughts control was build.