开发者

Access CustomAttribute in the view page in mvc3

开发者 https://www.devze.com 2023-03-22 14:25 出处:网络
I have created a custom attribute \'RoleAction\' and added to the model property开发者_StackOverflow中文版

I have created a custom attribute 'RoleAction' and added to the model property开发者_StackOverflow中文版

public class RoleActionAttribute : Attribute
{
    public string UserRole { get; set; }

    public RoleActionAttribute(string Role)
    {
        this.UserRole = Role;
    }

}


[RoleAction("Manager")] 
public EmployeeName

How to I get the RoleAction value (Manager) in my mvc view page.


You could use Reflection in order to fetch custom attributes:

var roleAction = (RoleActionAttribute)typeof(MyViewModel)
    .GetProperty("EmployeeName")
    .GetCustomAttributes(typeof(RoleActionAttribute), true)
    .FirstOrDefault();
if (roleAction != null)
{
    var role = roleAction.UserRole;
}

Another possibility is to use Metadata and make your custom attribute metadata aware by implementing the new IMetadataAware interface that was introduced in ASP.NET MVC 3:

public class RoleActionAttribute : Attribute, IMetadataAware
{
    public string UserRole { get; set; }

    public RoleActionAttribute(string Role)
    {
        this.UserRole = Role;
    }

    public void OnMetadataCreated(ModelMetadata metadata)
    {
        metadata.AdditionalValues["role"] = UserRole;
    }
}

and then:

var metaData = ModelMetadataProviders
    .Current
    .GetMetadataForProperty(null, typeof(MyViewModel), "EmployeeName");
if (metaData != null)
{
    string userRole = metaData.AdditionalValues["role"] as string;
}


You can use TempData for it.

0

精彩评论

暂无评论...
验证码 换一张
取 消