【问题标题】:How can I access C# class attributes inside a Razor engine view file?如何访问 Razor 引擎视图文件中的 C# 类属性?
【发布时间】:2012-10-11 17:37:31
【问题描述】:

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

C#类:

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

剃刀视图:

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

【问题讨论】:

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


    【解决方案1】:

    一种干净的方法是在 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)
    

    【讨论】:

      猜你喜欢
      • 2012-01-28
      • 1970-01-01
      • 1970-01-01
      • 2013-12-20
      • 1970-01-01
      • 1970-01-01
      • 2011-03-23
      • 2011-03-11
      • 1970-01-01
      相关资源
      最近更新 更多