简体   繁体   中英

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. How would I am stuck on the 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:

// 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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