是否有可能使模型属性属性为Asp中的特定角色所必需?净MVC
本文关键字:属性 定角色 MVC 有可能 模型 Asp 是否 | 更新日期: 2023-09-27 18:12:55
是否有可能只需要指定的角色来建模数据注释上的字段?
例如:[Display(Name = "Kurum")]
[Required(ErrorMessage = "Kurum Alanı Girişi Zorunludur.",Roles="user")]
public decimal? KurumKodu { get; set; }
我知道没有像Required(Roles="xxxx")
这样的参数,但我想知道有没有其他的解决方案?
谢谢。
您必须为此创建自定义验证属性。下面的代码可以帮助你做到这一点。
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; }
}
如果您想添加客户端验证(不显眼),那么请参阅下面的链接。
RequiredIf条件验证属性
可以使用
HttpContext.Current.User.IsInRole("USER_ROLE")
中的自定义验证属性类
我尝试了不同的方法,但我认为最好的地方是在视图上。比如:
@if (User.IsInRole("SystemAdministrator"))
{
<td>@Html.DisplayFor(model => model.KurumKodu)</td>
}