我有这个MVC页面,我有三个不同的“输入”元素,所有相同的类,使用jQuery自动完成。在其中任何一个我都在控制器中这样做:
[HttpGet]
public ActionResult GetAllItemsEdit(string data, string source)
{
List<TextValuePair> items = InventoryControlRepository.GetAllItemsTVP();
var result1 = items.Where(item => item.Text.Contains(data.ToUpper())).ToList();
return Json(result1, JsonRequestBehavior.AllowGet);
}
这些项目包含:
TextValuePair tvp = new TextValuePair();
tvp.Text = item.ItemNumber + " - " + item.ItemDescription + " - SN: " + item.SerialNumber;
tvp.Value = item.ItemNumber;
list.Add(tvp);
因此,必须根据源输入字段匹配TVP的Text
部分中的文本。知道怎么做吗?我需要以某种方式拆分item.Text
字段并检查基本上三列数据中的一列以匹配页面的输入。
感谢Pete的回答,我能够完成它。我不得不在模型中添加一个字段,本质上是一个搜索字段,其中包含我想要的Text字段值。
[HttpGet]
public ActionResult GetAllItemsEdit(string data, string source)
{
IEnumerable<ItemModel> models = InventoryControlRepository.GetAllItems();
switch (source)
{
case "txtFindSerial":
models = models.Where(x => x.SerialNumber.IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1);
break;
case "txtFindItem":
models = models.Where(x => x.ItemNumber.IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1);
break;
case "txtFindDescription":
models = models.Where(x => x.ItemDescription.IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1);
break;
}
var result1 = models.Select(item => new TextValuePair() { Text = item.SearchField, Value = item.ItemNumber }).ToList();
return Json(result1, JsonRequestBehavior.AllowGet);
}
答案 0 :(得分:1)
我会搜索您的初始项目(在您进入TextValuePair
列表之前)然后您可以执行类似
IEnumerable<Item> items = originalItemsList;
switch (source)
{
case "1": // or whatever this should be
items = items.Where(x => x.ItemNumber.IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1);
break;
case "2": // or whatever this should be
items = items.Where(x => x.ItemDescription.IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1);
break;
case "3": // or whatever this should be
items = items.Where(x => x.SerialNumber.IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1);
break;
}
var result1 = items.Select(item => new TextValuePair() { text = item.Text, Value = item.ItemNumber }).ToList();
return Json(result1, JsonRequestBehavior.AllowGet);
如果您不能使用初始对象,那么我可能会这样做
var result1 = items.Where(item => TextMatches(item.Text, data, source)).ToList();
然后有一个方法:
private static bool TextMatches(string text, string data, string source)
{
// you may want to chose a better delimiter if your text description contains a " - "
string[] textParts = text.Split(new string[] { " - " }, StringSplitOptions.None);
switch (source)
{
case "1": // or whatever this should be
return textParts[0].IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1;
case "2": // or whatever this should be
return textParts[1].IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1;
case "3": // or whatever this should be
return textParts[2].IndexOf(data, StringComparison.InvariantCultureIgnoreCase) > -1;
}
return false;
}