c# - 如何将 PropertyInfo[] 转换为 Dictionary<string,string>?

标签 c# asp.net-mvc-4 reflection dictionary html.dropdownlistfor

实际上,我需要将类的属性显示在 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")

关于c# - 如何将 PropertyInfo[] 转换为 Dictionary<string,string>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19396074/

相关文章:

asp.net-mvc - 登录后出现404.0错误。 Asp.Net MVC 和 IIS 7.5

javascript - 谷歌地图: Add click listener to each polygon

reflection - 如何使用反射初始化结构值字段?

c# - Try - Catch 返回策略

c# - SharpSVN:无法连接到 URL 上的存储库 |禁止访问

c# - 使用具有 Must、Must_Not 和 Should 条件的过滤器的 MultiMatch ElasticSearch 查询

c# - 使用 C# 中的输出参数和结果集读取 SP?

c# - 未找到 System.ComponentModel.DataAnnotations.Schema

c# - CSharpCodeProvider 符合接口(interface)

c# - 通过泛型方法传递类型的新实例