从 ViewModel 获取 [key] 属性 [英] Get [key] property from ViewModel
问题描述
我有一个具有 [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?
推荐答案
如果您对示例中的任何代码感到困惑或困惑,请发表评论,我会尽力提供帮助.
总而言之,您对使用 反射 遍历类型的元数据以获取具有分配给它们的给定属性的属性很感兴趣.
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屋!