从ViewModel获取[key]属性 [英] Get [key] property from ViewModel

查看:235
本文介绍了从ViewModel获取[key]属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有[key]属性的ViewModel,我想从该视图模型的实例中获取它.

I have a ViewModel which has a [key] property and i would like to get that from an instance of that view model.

我的代码看起来像这样(虚构模型)

My code looks something like this (fictional models)

class AddressViewModel
{
    [Key]
    [ScaffoldColumn(false)]
    public int UserID { get; set; } // Foreignkey to UserViewModel
}

// ... somewhere else i do:
var addressModel = new AddressViewModel();
addressModel.HowToGetTheKey..??

所以我需要从ViewModel中获取UserID(在这种情况下).我该怎么办?

So i need to get the UserID(in this case) from the ViewModel. How can i do this?

推荐答案

如果您对示例中的任何代码感到困惑或困惑,请添加注释,我将尽力提供帮助.

总而言之,您很有趣地使用 Reflection 遍历该类型的元数据以获得具有为其分配了给定属性的属性.

In summary, you are interesting in using Reflection to walk the meta-data of the type to get properties that have a given attribute assigned to them.

下面只是实现此目的的一种方法(有许多其他方法,也有许多提供相似功能的方法).

Below is just one way of doing this (there are many others and also many methods that provide similar functionality).

来自这个问题评论:

PropertyInfo[] properties = viewModelInstance.GetType().GetProperties();

foreach (PropertyInfo property in properties)
{
    var attribute = Attribute.GetCustomAttribute(property, typeof(KeyAttribute)) 
        as KeyAttribute;

    if (attribute != null) // This property has a KeyAttribute
    {
         // Do something, to read from the property:
         object val = property.GetValue(viewModelInstance);
    }
}

像乔恩(Jon)所说,请处理多个KeyAttribute声明以避免出现问题.此代码还假定您正在修饰public属性(不是非公共属性或字段),并且需要System.Reflection.

Like Jon says, handle multiple KeyAttribute declarations to avoid issues. This code also assumes you are decorating public properties (not, non-public properties or fields) and requires System.Reflection.

这篇关于从ViewModel获取[key]属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆