如何在Razor引擎视图文件中访问C#类属性?

时间:2012-10-11 17:37:32

标签: c# .net asp.net-mvc razor attributes

如何在Razor引擎视图文件中访问C#类属性?

C#class:

[Name="Test"]
public class OrderProgressPage
{
    bool isComplete();
}

Razor观点:

@model ViewModels.OrderProgressPage
<ul>
    <li>@GETAttribute(Name,Model)</li>
<ul>

1 个答案:

答案 0 :(得分:3)

一种干净的方法是使用Razor文件中的本地函数

@functions
{
    private Test GetTestAttribute(object obj)
    {
        // TODO: This returns null if TestAttribute was not on the class
        TestAttribute myAttribute =
            Attribute.GetCustomAttribute(obj, typeof (TestAttribute)) as TestAttribute;
    }
}

<li>@GetTestAttribute(myClassInstance)</li>

参考:http://msdn.microsoft.com/en-us/library/71s1zwct.aspx

如果您需要传入要检查的属性名称,可以使用

Type.GetType(string typeName)

根据您的操作,您还可以将GetTestAttribute更改为具有签名的通用函数,如

private T GetAttribute<T>(object obj)