c# - ASP.NET MVC 中基于不同角色的条件只读/可编辑属性

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

我们正在开发一个类似工作流的应用程序。我们希望为不同的用户角色显示相同的表单(具有相同的 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 是:

<input class="form-control global" id="ServiceID" name="ServiceID" type="text" value="" readonly="readonly">

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

覆盖什么方法?或者还有其他解决方案吗?

谢谢。

最佳答案

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

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

但这不是预期的用途。

一些选项包括

  1. 设置 View 模型或 ViewBag 属性(比如 bool isReadOnly) 然后根据值添加 html readonly 属性。 this answer 中显示了此方法的示例
  2. 创建您自己的接受 View 模型或 ViewBag 的 html 助手 属性(property)。 this answer 中显示了此方法的示例
  3. 如果您想使用 DataAnnotations,请创建您自己的属性 继承Attribute并实现IMetadataAware然后创建 你自己的 html 助手,它读取属性属性并添加 html 属性。 this answer 中显示了此方法的示例

关于c# - ASP.NET MVC 中基于不同角色的条件只读/可编辑属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28163884/

相关文章:

c# - ASP.NET MVC - 自动注销

c# - 从 ASP.net webform 中的 c# 类调用方法

c# - 如何使用 Eval() 来引用 asp Repeater 中 SortedDictionary 中的值?

javascript - 在指令中定义 ng-model 后,Angularjs ng-model 不起作用

asp.net - 如何在 IIS 7.5 上调试经典 asp 页面 Visual Studio 2010?

asp.net 成员(member)资格 IsApproved false 但仍允许登录

asp.net-mvc - MVC5 - 用于特定操作的 block Controller 输出缓存

c# - WPF 列表框 DisplayMemberPath 和 SelectedValuePath

c# - String.ToLowerInvariant() 如何确定它必须转换成什么字符串/字符?

ASP.NET:如何更改验证失败的控件的背景颜色?