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,它检查值是否存在,但前提是当前用户具有特定角色。

我真的需要一个自定义的 Display 属性,但由于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 回答