asp.net mvc 3 在模型上运行验证
如何在模型上运行所有 DataAnnotation 验证?
我正在从代码构建模型实例,并且没有模型状态绑定或任何东西。我只想针对它运行所有验证...我正在使用 EF CodeFirst。
public class Category
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
cat = new Category();
if (cat.IsValid()) { /* blah */ } // i want something like this
我知道这可能是一个愚蠢的问题,但我似乎无法在任何地方找到答案。
How can i run all DataAnnotation validations on model?
I'm building a model instance from code and i don't have no modelstate binding or anything. I just want to run all my validations against it... I am using EF CodeFirst.
public class Category
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
cat = new Category();
if (cat.IsValid()) { /* blah */ } // i want something like this
I know it's probably a stupid question but i can't seem to find an answer anywhere..
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这类似于这个关于单元测试数据注释的问题。您可以添加与此类似的扩展方法:
This is similar to this question about unit testing data annotations. You could add an extension method similar to this:
这个问题的标题包括 ASP.net MVC。
请注意,Validator 类和 MVC 验证存在细微差别。
例如:
如果您想要运行 MVC 的验证并填充 ModelState,您可以调用 TryValidateModel 或 ValidateModel。
如果您不想填充 ModelState,请在控制器中使用此代码片段。
The title of this question includes ASP.net MVC.
Please be aware that the Validator class and MVCs validation has subtle differences.
For example:
If you want to run MVC's validation and populate the ModelState, you can call the TryValidateModel or ValidateModel.
if you don't want to populate the ModelState, use this code snippet in your controller.