我们正在开发一个类似工作流的应用程序。我们希望为不同的用户角色显示相同的表单(具有相同的 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 没有影响。它所做的只是设置 ModelMetaData
的 IsReadOnly
属性。您当然可以使用类似的东西读取值
@if (ViewData.ModelMetadata.Properties.Where(p => p.PropertyName == "SomeProperty").First().IsReadOnly)
{
// add the readonly="readonly" attribute to the control
但这不是预期的用途。
一些选项包括
- 设置 View 模型或
ViewBag
属性(比如bool isReadOnly
) 然后根据值添加 htmlreadonly
属性。 this answer 中显示了此方法的示例 - 创建您自己的接受 View 模型或
ViewBag
的 html 助手 属性(property)。 this answer 中显示了此方法的示例 - 如果您想使用 DataAnnotations,请创建您自己的属性
继承
Attribute
并实现IMetadataAware
然后创建 你自己的 html 助手,它读取属性属性并添加 html 属性。 this answer 中显示了此方法的示例
关于c# - ASP.NET MVC 中基于不同角色的条件只读/可编辑属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28163884/