在MVC之外使用ASP.Net MVC数据注释
我想知道是否有一种方法可以在没有MVC网站的情况下使用ASP.Net的数据注释。
我的例子是我有一个曾经创建过的类需要validation,否则会抛出错误。 我喜欢数据注释方法,而不是initaliser触发的一堆if块。
有没有办法让这个工作?
我以为它会是这样的:
有任何想法吗? 我必须承认我还没有将MVC框架添加到我的项目中,因为我希望我可以使用数据注释类System.ComponentModel.DataValidation
这是一个例子:
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; public class Foo { [Required(ErrorMessage = "the Bar is absolutely required :-)")] public string Bar { get; set; } } class Program { public static void Main() { var foo = new Foo(); var results = new List(); var context = new ValidationContext(foo, null, null); if (!Validator.TryValidateObject(foo, context, results)) { foreach (var error in results) { Console.WriteLine(error.ErrorMessage); } } } }
但说实话, FluentValidationfunction更强大。
上述就是C#学习教程:在MVC之外使用ASP.Net MVC数据注释分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1030341.html