是否可以仅将指定的角色设置为数据转换的模型字段?
例如:
[Display(Name = "Kurum")]
[Required(ErrorMessage = "Kurum Alanı Girişi Zorunludur.",Roles="user")]
public decimal? KurumKodu { get; set; }
我知道有像Required(Roles="xxxx")
之类的参数,但我想知道还有其他解决办法吗?
感谢。
答案 0 :(得分:1)
您必须为此创建自定义验证属性。下面的代码可以帮助您做到这一点。
public class RequiredIfAttribute : RequiredAttribute
{
private string PropertyName { get; set; }
private object DesiredValue { get; set; }
public RequiredIfAttribute(string propertyName, object desiredvalue)
{
PropertyName = propertyName;
DesiredValue = desiredvalue;
}
protected override ValidationResult IsValid(object value, ValidationContext context)
{
object instance = context.ObjectInstance;
Type type = instance.GetType();
Object proprtyvalue = type.GetProperty(PropertyName).GetValue(instance, null);
if (proprtyvalue.ToString() == DesiredValue.ToString())
{
ValidationResult result = base.IsValid(value, context);
return result;
}
return ValidationResult.Success;
}
}
然后您必须使用此属性装饰您的媒体资源 (阅读代码中的注释以便理解)
public class User
{
/// <summary>
/// Gets or Sets Usertype.
/// </summary>
public string UserType { get; set; }
/// <summary>
/// Gets or Sets KurumKodu.
/// Here "Usertype" is property. In that you have to assign current user's role.
/// "user" is constant role. If "UserType" has value as "user" then this will be required.
/// </summary>
[RequiredIf("UserType", "user", ErrorMessage = "It is required")]
public decimal KurumKodu { get; set; }
}
如果您想添加客户端验证(不引人注意),请参阅以下链接。
答案 1 :(得分:0)
您可以使用
HttpContext.Current.User.IsInRole("USER_ROLE")
在您的自定义验证属性类
中答案 2 :(得分:-2)
我尝试了不同的方法,但我到了这一点,最好的地方就是在视野中。类似的东西:
@if (User.IsInRole("SystemAdministrator"))
{
<td>@Html.DisplayFor(model => model.KurumKodu)</td>
}