如何将MetadataTypeAttribute与扩展类一起使用

时间:2012-12-05 12:46:43

标签: c# asp.net-mvc-3 asp.net-mvc-4

我想向DisplayAttribute实体(来自另一个项目)添加Client,但不希望使用特定于MVC或UI层的属性污染我的实体。所以我计划通过将元数据类应用于来自实体的视图模型继承来添加DisplayAttribute

如果我从Client实体继承,然后尝试使用MetadataTypeAttribute添加显示属性,则它不会显示在浏览器中。有谁知道我如何实现分离以及能够向我的实体添加元数据的功能?

Client实体类:

public class Client
{
    private string firstName;

    private string lastName;

    private string homeTelephone;

    private string workTelephone;

    private string mobileTelephone;

    private string emailAddress;

    private string notes;

    public Title Title { get; set; }

    public string FirstName
    {
        get { return this.firstName ?? string.Empty; }

        set { this.firstName = value; }
    }

    public string LastName
    {
        get { return this.lastName ?? string.Empty; }

        set { this.lastName = value; }
    }

    public string FullName
    {
        get
        {
            List<string> nameParts = new List<string>();

            if (this.Title != Title.None)
            {
                nameParts.Add(this.Title.ToString());
            }

            if (this.FirstName.Length > 0)
            {
                nameParts.Add(this.FirstName.ToString());
            }

            if (this.LastName.Length > 0)
            {
                nameParts.Add(this.LastName.ToString());
            }

            return string.Join(" ", nameParts);
        }
    }

    public Address Address { get; set; }

    public string HomeTelephone
    {
        get { return this.homeTelephone ?? string.Empty; }

        set { this.homeTelephone = value; }
    }

    public string WorkTelephone
    {
        get { return this.workTelephone ?? string.Empty; }

        set { this.workTelephone = value; }
    }

    public string MobileTelephone
    {
        get { return this.mobileTelephone ?? string.Empty; }

        set { this.mobileTelephone = value; }
    }

    public string EmailAddress
    {
        get { return this.emailAddress ?? string.Empty; }

        set { this.emailAddress = value; }
    }

    public string Notes
    {
        get { return this.notes ?? string.Empty; }

        set { this.notes = value; }
    }

    public Client()
    {
        this.Address = new Address();
    }
}

ClientViewModel视图模型类:

[MetadataType(typeof(ClientMetaData))]
public class ClientViewModel : Client
{
    internal class ClientMetaData
    {
        [Display(ResourceType = typeof(ResourceStrings), Name = "Client_FirstName_Label")]
        public string FirstName { get; set; }
    }
}

1 个答案:

答案 0 :(得分:2)

我认为您已将typeof参数更改为:

[MetadataType(typeof(ClientViewModel.ClientMetaData))]
public class ClientViewModel : Client
{
    internal class ClientMetaData
    {
        [Display(ResourceType = typeof(ResourceStrings), Name = "Client_FirstName_Label")]
        public string FirstName { get; set; }
    }
}