【发布时间】:2014-02-13 00:03:41
【问题描述】:
我有一个 MVC4 程序,其中有一个下拉列表,其中列出了模型的所有属性。我希望用户能够选择哪个属性,然后在文本框中键入要搜索的字符串值。问题是我无法使用下拉列表的值动态更改查询。
public ActionResult SearchIndex(string searchString, string searchFields)
{
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 = item.Name});
}
IEnumerable<SelectListItem> enumSelectList = selectListItems;
ViewBag.SearchFields = enumSelectList;
var bloodSearch = from m in db.BloodStored
select m;
if (!String.IsNullOrEmpty(searchString))
{
PropertyInfo selectedSearchField = getType(searchFields);
string fieldName = selectedSearchField.Name;
//Dynamic Linq query this is how it needs to be set up to pass through linq.dynamic without exception
bloodSearch = bloodSearch.Where("x => x." + fieldName + " == " + "@0", searchString).OrderBy("x => x." + fieldName);
return View(bloodSearch);
}
return View(bloodSearch);
}
这是我的 getType 方法
public PropertyInfo getType(string searchFields)
{
var first = db.BloodStored.First();
foreach (var item in first.GetType().GetProperties())
{
if(searchFields == item.Name)
{
return item;
}
}
return null;
}
我已经更新了我的代码以反映工作查询,它可以帮助其他任何人。 这是我从Dynamic query with LINQ won't work找到答案的帖子的链接
【问题讨论】:
标签: c# asp.net-mvc-4 lambda