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.
精彩评论