![](/img/trans.png)
[英]ASP.NET MVC : transfering query data to model class object in controller
[英]Mapping Data Annotation of a Model object to Custom Class object .net mvc
我想知道如何將模型對象映射到更通用的類對象中,並將DataAnnotation的值保存到指定字段。
以我的示例模型為例。 我想將1個Model對象映射到1個FieldSetModel對象,該對象包含具有值的Model字段列表以及DataAnnotation提供的alla元數據。
等等..
模型
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
FieldSetModel我想將值和DataAnnotationValues映射到與View相關的此類:
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;
}
}
如前所述,您可以從以下問題中獲取信息的屬性: 如何從代碼中檢索數據注釋? (以編程方式)
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));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.