简体   繁体   English

使用反射填充下拉列表

[英]Populating Dropdown using Reflection

I am using MVC4 and what I want to do is use a dropdown connected to my search box to search for the selected property. 我正在使用MVC4,我想做的是使用连接到我的搜索框的下拉列表来搜索选定的属性。 How would I am stuck on the Text= prop.Name. 我将如何停留在Text = prop.Name上。 How could I go through and access all of the properties using this. 我该如何使用它来访问和访问所有属性。

My Controller 我的控制器

public ActionResult SearchIndex(string searchString)
    {
        var selectListItems = new List<SelectListItem>();

        var first = db.BloodStored.First();
        foreach(var item in first.GetType().GetProperties())
        {
            selectListItems.Add(new SelectListItem(){ Text = item.Name, Value = selectListItems.Count.ToString()});
        }
        IEnumerable<SelectListItem> enumSelectList = selectListItems;
        ViewBag.SearchFields = enumSelectList;


        var bloodSearch = from m in db.BloodStored
                          select m;

        if (!String.IsNullOrEmpty(searchString))
        {
            bloodSearch = bloodSearch.Where(s => string.Compare(GetValue(s, propertyName), searchString) == 0);
        }
        return View(bloodSearch);
    }

The selectlist is working now I just need to go over my searchstring and how to pass two parameters now. 现在,选择列表正在工作,我只需要遍历我的搜索字符串以及现在如何传递两个参数。

I'm not quite sure what you're asking. 我不太确定您要问什么。 If you want to create a list of objects with the property Text set to the property name of the object, you could get the first object in the BloodStored enumerable and create a list of anonymous types: 如果要创建属性为Text的对象列表,将其设置为对象的属性名称,则可以获取BloodStored枚举中的第一个对象,并创建匿名类型列表:

// Get one instance and then iterate all the properties
var selectListItems = new List<object>();
var first = db.BloodStore.First();
foreach(var item in first.GetType().GetProperties()){
    selectListItems.Add(new (){ Text = item.Name});
}

ViewBag.SearchFields = selectListItems;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM