ASP.NET MVC数据在Web项目中注释域模型

时间:2011-02-09 21:30:42

标签: asp.net-mvc asp.net-mvc-3

我之前在博客上看到过如何做到这一点,但我忘记了在哪里或如何做。假设我在类库中有一个域。我想数据注释这个域的属性作为我在web项目中的viewmodel。

我如何做到这一点?

例如。这个域名在我的类库中:

public class Person {
   public int Id {get; set;}
   public string FirstName {get; set;}
}

在我的网络项目中,有这样的:

//Do i need to set some attribute here?
public class CreatePersonViewModel{

   [Required()]
   [DisplayName("First Name")]
   public string FirstName {get; set;}
}

此代码可以在没有工具的情况下映射到Person。可能是部分或某种东西。

4 个答案:

答案 0 :(得分:4)

使用视图模型的整个想法是将它与域模型分离,并使某些东西适应视图的需要。视图模型应在Web项目中声明,并包含此特定视图可能需要的所有必需属性和格式属性。不应使用任何视图特定数据注释污染域模型。所以如果你的模型看起来像这样:

public class Person {
   public int Id { get; set; }
   public string FirstName { get; set; }
}

您可以拥有以下视图模型:

public class CreatePersonViewModel {
   [Required]
   [DisplayName("First Name")]
   public string FirstName { get; set; }
}

然后让控制器从某个存储库中获取模型,将其映射到视图模型(AutoMapper可以在这里帮助您)并将视图模型传递给视图。

答案 1 :(得分:1)

你在谈论这类事吗?:

using System.ComponentModel.DataAnnotations;

public MyClass
{


    [DisplayName("Street Address")]
    public string StreetAddress { get; set; }

}

编辑:

如果您需要像实体一样将数据注释添加到生成的类中:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel;

namespace Something

{
    [MetadataType(typeof(MetaMyClass))]
    public partial class MyClass
    {
          //You can just leave this empty if you have nothing additional to add to the class

    }

    public class MetaMyClass
    {
        [DisplayName("Street Address")]
        public string StreetAddress { get; set; }
    }
 }

答案 2 :(得分:1)

您的意思是注释您的域对象或视图模型对象吗?

使用System.ComponentModel.DataAnnotations验证属性(并从ValidationAttribute派生您自己的任何属性),您可以在模型绑定点验证绑定到viewmodel属性的值。

Scott Guthrie有 detailed blog post about Model validation with data annotation validation attributes

编辑:您在另一张海报的评论中说您的类型已经存在。您可以将MetadataTypeAttribute添加到现有类型,以指示包含要应用于现有类型属性的验证逻辑的其他类型。

答案 3 :(得分:1)

您可以为数据注释属性创建“好友”类

[MetadataType(typeof(ResourceMetadata))]
public partial class Resource
{
   public object Value { get; set; }
}

public class ResourceMetadata
{
  // The metadata class can define hints  

  [UIHint("ResourceValue")]
  public object Value { get; set; }
}