【问题标题】:How to access other Model field in custom Model field attribute?如何访问自定义模型字段属性中的其他模型字段?
【发布时间】:2012-06-09 05:20:08
【问题描述】:

问题是我试图在 asp.net mvc3 中创建一个自定义模型字段属性需要访问其他模型字段。例如命名为“PersonId”。

所以我有一个这样的模型

public class PersonWoundModel : IAppointmentModel
    {

        public int PersonId { get; set; }

        [CustomAttribute("PersonId")]
        public FillInList Positions { get; set; }
}

我有自定义属性

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class CustomAttribute : Attribute, IMetadataAware
    {
        public int PersonId { get; private set; }


        public CustomAttribute(bool allowDelete, bool allowEdit, string htmlHelpers)
        {
           //i need to get a PersonId here somehow.. reflection or any other method.
        }
}

所以基本上我需要在 [CustomAttribute] 中获取 aPersonId 字段以供进一步使用。我正在考虑使用反射,但不知道如何在那里获取模型对象。非常感谢大家的帮助。

【问题讨论】:

    标签: asp.net-mvc-3 model custom-attributes system.reflection .net-reflector


    【解决方案1】:

    你不能 - 因为没有模型对象。

    您的属性在元数据中是“序列化的” - 即构造它所需的字段是序列化的,因此它们必须是编译时已知的文字。当您使用 GetCustomAttributes 之类的方法对模型类使用反射时,将调用构造函数。但是到那时你(在你的代码中)可能会有一些对象要处理。

    【讨论】:

    • 是否有可能以某种方式获得模型对象?
    • 正如我所说 - 不,构造函数中有哪里?:)? - 正如我所说,当您对模型类型使用反射时,它将被调用。如果您急需 any 对象 - 只需使用 'new' 构造一个
    • 该属性可以在任何模型中的任何位置使用。我不需要任何对象:) 我需要 PersonId 所在的那个:)。我的意思是可以在属性类的任何地方获取模型对象:)
    • 不是“自动”——您应该在其他地方构建模型对象。您可以定义 PersonId 类型的自定义属性的属性并设置它。
    • 我不需要自动拥有它。 :))) 我需要以某种方式使用反射在属性类中获取它。我知道如何在别处设置它。 :) 是的,它目前在其他地方构建 :) 你能给出任何代码示例如何实现你的最后一条评论吗?
    猜你喜欢
    • 2019-03-22
    • 2012-10-13
    • 1970-01-01
    • 2020-11-29
    • 2022-01-24
    • 1970-01-01
    • 2011-06-06
    • 2019-09-06
    • 1970-01-01
    相关资源
    最近更新 更多