1

其实我需要我的课的属性显示在mvc下拉列表中。我使用反射来获得这些东西。但现在我的问题是让它们作为关键值对在下拉列表中显示它们。如何将PropertyInfo []转换为Dictionary <string,string>?

我使用下面的代码...

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 
+0

那么是什么对象你试图从中获取值?你有一个新的'ViewContactModel',但可能它实际上并不包含联系人。这里没有关于哪个*联系人获取... –

+1

的信息关键是什么?你想要什么价值? – Damith

+0

我不想要一个特定的联系人..我只查找类Entity.Data.Contact中的属性。它具有名称,移动,电子邮件,国家,城市,国家等属性..我想在下拉的那些proprties .. –

回答

1

如果必须使用字典和假设名称和每个下拉项的值是属性名称本身,你可以使用大意如下的东西:

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") 
+0

非常感谢...它为我节省了一天的工作..它完美的工作..并由方式,如果我只需要一些属性...如何得到它们?有没有解决方案 –

+1

Abhijeet先生你能帮我吗? –

+1

答复已更新。您可以传递一组字符串作为您需要的属性名称。 GetProperties (“FirstName”,“LastName”)如果您需要所有属性,请使用GetProperties ()。希望这会有所帮助 –

相关问题