2

データ注釈といくつかのカスタム テンプレートを使用して、多くのビューを生成しています。

public class Container
{
    [HiddenInput(DisplayValue = false)]
    public string Key { get; set; }

    [Display(Name = "Full Name")]
    [RequiredForRole("Editor"), StringLength(30)]
    public string Name { get; set; }

    [Display(Name = "Short Name")]
    [RequiredForRole("Editor"), StringLength(10)]      
    public string ShortName { get; set; }

    [Display(Name="Maximum Elements Allowed")]
    [RequiredForRole("Admin")]
    public int MaxSize { get; set; }

    [Display(Name = "Components")]
    public IList<Component> Components{ get; set; }
}

ビューでは、、、などを使用し@Html.DisplayForModel()ます@Html.EditorForModel

特定のプロパティは、一部のロールのユーザーが編集できるようにする必要がありますが、他のロールでは非表示にする必要があります。ご覧のとおりRequiredForRole、現在のユーザーが特定の役割を持っている場合にのみ、値が存在することを確認するカスタム検証属性を実装しました。

カスタム表示属性が本当に必要ですが、DisplayAttribute封印されているため、これは不可能のようです。

さまざまな種類のユーザー向けにさまざまなテンプレートを多数用意することは避けたいと考えています。または、ビューに誰が何を表示するかというロジックをプッシュし始めたいと考えています。この問題を解決する最もきちんとした方法は何ですか?

4

1 に答える 1

3

たぶん、このようなもの。(大きな)問題は、現在のユーザーの役割を確認する方法です...

public class VisibleForRoleAttribute : Attribute, IMetadataAware
    {
        public string[]  Roles { get; set; }
        public VisibleForUserAttribute(string[] roles)
        {
            Roles = roles;
        }
        public void OnMetadataCreated(ModelMetadata metadata)
        {
            var toShow =  Roles.Any(IsUserInRole);
            metadata.ShowForDisplay = metadata.ShowForEdit =  toShow; // or just ShowForEdit

        }
        private bool IsUserInRole(string roleName)
        {
            return HttpContext.Current != null &&
                   HttpContext.Current.User != null &&
                   HttpContext.Current.User.IsInRole(roleName); //if you use MembershipProvider
        }
    }

利用方法

[VisibleForRole(new[]{"Administrator", "Editor"})]
于 2012-08-30T10:26:54.843 に答える