如何将属性信息[]转换为字典<字符串,字符串>
本文关键字:字符串 字典 转换 属性 信息 | 更新日期: 2023-09-27 18:35:28
>实际上我需要在 mvc 下拉列表中显示我的类的属性。我正在用反思来获得这些东西。但是现在我的问题是将它们作为键值对获取以在下拉列表中显示它们。
我正在使用下面的代码...
public static Dictionary<string,string> SetProperties()
{
Type T = Type.GetType("Entity.Data.Contact");
PropertyInfo[] resultcontactproperties = T.GetProperties();
ViewContactModel viewobj = new ViewContactModel();
viewobj.properties = resultcontactproperties;
Dictionary<string, string> dic = new Dictionary<string, string>();
return dic;
}
那么如何将它们转换为字典以在下面的下拉列表中获取它们...?
@Html.DropDownListFor(m=>m.properties, new SelectList(Entity.Data.ContactManager.SetProperties(),"",""), "Select a Property")
Well this is my ViewContactModel
public class ViewContactModel
{
public List<Entity.Data.Contact> Contacts;
public int NoOfContacts { get; set; }
public Paging pagingmodel { get; set; }
public PropertyInfo[] properties { get; set; }
}
In the view I'm using this model
如果必须使用字典,并假定每个下拉项的"名称"和"值"是属性名称本身,则可以使用以下行:
public static Dictionary<string, string> GetProperties<T>(params string[] propNames)
{
PropertyInfo[] resultcontactproperties = null;
if(propNames.Length > 0)
{
resultcontactproperties = typeof(T).GetProperties().Where(p => propNames.Contains(p.Name)).ToArray();
}
else
{
resultcontactproperties = typeof(T).GetProperties();
}
var dict = resultcontactproperties.ToDictionary(propInfo => propInfo.Name, propInfo => propInfo.Name);
return dict;
}
@Html.DropDownListFor(m=>m.properties, new SelectList(
Entity.Data.ContactManager.GetProperties<Contact>(),"Key","Value"),
"Select a Property")