【问题标题】:Conditional ReadOnly/Editable Attribute based on Different Roles in ASP.NET MVCASP.NET MVC中基于不同角色的条件只读/可编辑属性
【发布时间】:2015-01-27 05:35:27
【问题描述】:

我们正在开发一个类似工作流的应用程序。我们希望为不同的用户角色显示相同的表单(具有相同的ViewModel 和相同的View)。我们希望根据特定的用户角色使某些字段只读不可编辑。

ViewModel 就像:

public class ServiceViewModel
{
    [EditableIfInRoles("Administrator", "Editor")]
    public string ServiceId { get; set; }
}

我们计划创建一个自定义ReadOnlyAttribute,例如:

public class EditableIfInRolesAttribute : EditableAttribute
{
    private IEnumerable<string> _allowedRoles; 

    public EditableIfInRolesAttribute(params string[] allowedRoles) : base(true)
    {
        _allowedRoles = allowedRoles;
    }

    /// <summary>
    /// Currently we don't know which method to override
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public override bool IsEditable(object value)
    {
        return _allowedRoles.Any(e => HttpContext.Current.User.IsInRole(e));
    }
}

我们期望未经授权的用户角色呈现的 HTML 是:

&lt;input class="form-control global" id="ServiceID" name="ServiceID" type="text" value="" readonly="readonly"&gt;

如何创建继承ReadOnlyAttribute 或“EditableAttribute”的自定义属性,因为它们都是密封类?

重写什么方法?或者有没有其他解决方案?

谢谢。

【问题讨论】:

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


    【解决方案1】:

    你对EditableAttribute用法的误解,它对html助手生成的html没有影响。它所做的只是设置ModelMetaDataIsReadOnly 属性。您当然可以使用类似的方法读取值

    @if (ViewData.ModelMetadata.Properties.Where(p => p.PropertyName == "SomeProperty").First().IsReadOnly)
    {
      // add the readonly="readonly" attribute to the control
    

    但这不是预期的用途。

    一些选项包括

    1. 设置视图模型或ViewBag 属性(比如bool isReadOnly) 然后根据值添加html readonly 属性。这种方法的一个例子显示在this answer
    2. 创建您自己的接受视图模型或ViewBag 的 html 助手 财产。这种方法的一个例子显示在this answer
    3. 如果您想使用 DataAnnotations,请创建您自己的属性 继承Attribute并实现IMetadataAware然后创建 您自己的 html 助手读取属性属性并添加 html 属性。这种方法的一个例子显示在this answer

    【讨论】:

      猜你喜欢
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-18
      • 2011-09-03
      相关资源
      最近更新 更多