3

我想向实体添加一个DisplayAttributeClient来自另一个项目),但不想用特定于 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; }
    }
}
4

1 回答 1

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; }
    }
}
于 2013-02-06T18:07:25.640 回答