获取数据注解从模型属性 [英] Get Data Annotations attributes from model
问题描述
我要创建自定义的客户端验证,但我想定义的验证规则通过数据注释在业务逻辑层属性。我怎样才能访问运行时模型验证属性?
I want to create custom client-side validator, but I want define validation rules via Data Annotations attributes at business logic layer. How can I access model validation attributes in runtime?
我想写'发电机',它会转换成该code:
I want to write 'generator', which will convert this code:
public class LoginModel
{
[Required]
[MinLength(3)]
public string UserName { get; set; }
[Required]
public string Password { get; set; }
}
到这一个:
var loginViewModel= {
UserName: ko.observable().extend({ minLength: 3, required: true }),
Password: ko.observable().extend({ required: true })
};
但不从的.cs源,当然。 =)
But not from .cs sources, of course. =)
也许反射?
UPD
我发现这个方法:<一href=\"http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.getunobtrusivevalidationattributes%28v=vs.108%29.aspx\"相对=nofollow> MSDN 。但不知道如何使用它。
I've found this method: MSDN. But can't understand how to use it.
推荐答案
这是在通用办法如何做到这一点:
This is the universal way how to do this:
private string GenerateValidationModel<T>()
{
var name = typeof(T).Name.Replace("Model", "ViewModel");
name = Char.ToLowerInvariant(name[0]) + name.Substring(1);
var validationModel = "var " + name + " = {\n";
foreach (var prop in typeof(T).GetProperties())
{
object[] attrs = prop.GetCustomAttributes(true);
if (attrs == null || attrs.Length == 0)
continue;
string conds = "";
foreach (Attribute attr in attrs)
{
if (attr is MinLengthAttribute)
{
conds += ", minLength: " + (attr as MinLengthAttribute).Length;
}
else if (attr is RequiredAttribute)
{
conds += ", required: true";
}
// ...
}
if (conds.Length > 0)
validationModel += String.Format("\t{0}: ko.observable().extend({{ {1} }}),\n", prop.Name, conds.Trim(',', ' '));
}
return validationModel + "};";
}
用法:
string validationModel = GenerateValidationModel<LoginModel>();
输出:
var loginViewModel = {
UserName: ko.observable().extend({ minLength: 3, required: true}),
Password: ko.observable().extend({ required: true}),
};
这是好主意,缓存输出
It's good idea to cache the output
这篇关于获取数据注解从模型属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!