将模型对象的数据注释映射到自定义类对象 .net mvc

本文关键字:对象 自定义 net mvc 注释 模型 数据 映射 | 更新日期: 2023-09-27 18:30:54

我想知道如何将模型对象映射到更通用的类对象并将DataAnnotation的值保存到指定字段。

例如,我的示例模型。我想将 1 个模型对象映射到 1 个 FieldSetModel 对象,其中包含具有值的模型字段列表,以及 DataNotation 提供的所有元数据。

  • Model.Name -> FieldSet.FormModel[1].id
  • Model.Name ->FieldSet.FormModel[1].name
  • 型。(DataAnnotation(MaxLenght) -> FieldSet.FormModel[1]。麦克斯朗特
  • 型。(DataAnnotation(Display) -> FieldSet.FormModel[1]。显示名称

等。。

    public virtual Int32 Id { get; protected set; }
    #region Login
    [Required,MaxLength(30)]
    [Display(Name = "Nome Utente")]
    public virtual string UserName { get; set; }
    [Required, MaxLength(200),DataType(DataType.EmailAddress)]
    [Display(Name = "Email")]
    public virtual string Email { get; set; }
    [Required]
    [Display(Name = "Password"),DataType(DataType.Password),MinLength(6)]
    [StringLength(100, ErrorMessage="La lunghezza di {0} deve essere di almeno {2} caratteri.", MinimumLength=6)]
    public virtual string Password { get; set; }
    #endregion

字段集模型我想将值和数据注释值映射到与视图相关的此类:

   public class FieldSetModel
{
    public string Title;
    public List<Field> FormModel = new List<Field>();
}
public class Field{
    public string Id            { get; private set; }
    public string Name          { get; private set; }
    public string DisplayName;
    public string DataType = "text";
    public int MaxLenght = 100;
    public int MinLenght = 0;
    public string FormatErrorMessage =  "Formato non valido";
    public string RangeErrorMessage =   "Range non valido";
    public string RequiredErrorMessage = "Valore  Non Corretto";
    public string Pattern;
    public string DisplayFormat;
    public string Value;
    public bool Error;
    public Field(string name)
    {
        this.Name = name;
        this.Id = name;
    }
}

将模型对象的数据注释映射到自定义类对象 .net mvc

正如您已经提到的,您可以使用以下问题中的信息获取属性: 如何从代码中检索数据注释?(以编程方式)

public static T GetAttributeFrom<T>(this object instance, string propertyName) where T : Attribute
{
    var attrType = typeof(T);
    var property = instance.GetType().GetProperty(propertyName);
    return (T)property .GetCustomAttributes(attrType, false).First();
}

使用反射获取属性及其值也非常简单。你可以参考这个问题:如何获取类的属性列表?

class Foo {
    public int A {get;set;}
    public string B {get;set;}
}
...
Foo foo = new Foo {A = 1, B = "abc"};
foreach(var prop in foo.GetType().GetProperties(BindingFlags.Public)) {
    Console.WriteLine("{0}={1}", prop.Name, prop.GetValue(foo, null));
}