如何在文本中获取多个或单个值



我有一个搜索模型。

public class Search{
public string SearchId{ get; set;}
}

我在控制器的asp.net mvc操作中得到了这个

[HttpPost]
public ActionResult Search(Search search){
...
...
}

当用户在文本框中设置ID值时,我使用实体框架进行搜索。

但我的客户想要搜索多个逗号分隔的id,就像下面的一样

1,2,3,4,5

所以我想了解SearchId值是多个还是单个。那么我怎么能理解呢?使用模式测试还是其他?

您可以将搜索更改为类似字符串的搜索,并将其拆分为int数组:

[HttpPost]
public ActionResult Search(string search)
{
int[] ints = search.Split(',').Select(int.Parse).ToArray();

var results = from customer in context.Customers
where ints.Contains(customer.Id)
select customer;
//todo: handle results
}

如果数组中只有一个ID,那么应该不会有什么不同。

试试这个:

[HttpPost]
public ActionResult Search(Search search){
var numbers = search.SearchId.Split(',').Select(Int32.Parse).ToList();

//to understand the SearchId value if multiple or single
if(numbers.Count == 1){
// SearchId value is single
}
else if(numbers.Count > 1)
//SearchId value has multiple value
}

如果你只需要了解SearchId值是多个还是单个,你可以用"到数组并检查数组长度(但我不会说这是最好的解决方案(。

[HttpPost]
public ActionResult Search(Search search){
var ids = search.SearchId.Split(",", StringSplitOptions.RemoveEmptyEntries);
bool isMultiple = ids.Length > 1;
}

但是,如果您的SearchId只包含逗号分隔的整数字符串,则有更好的方法。首先,你需要从更改合同

public ActionResult Search(Search search)

public ActionResult Search(int[] ids)

因为它简化了过程,而且您不需要将SearchId字符串拆分为子字符串数组,然后将数组中的每个元素解析为integer。在这种情况下,您应该理解,您正在尝试解析用户的输入,并且有可能在输入字符串中得到无法解析为整数的内容(例如"1,2,3,e,t"(,您需要通过try-catch块包装int.parse或使用int.TryParse。另一件事可能是,你总是返回和数组作为搜索响应,如果用户传递单个id或多个id,你不需要担心,因为你总是返回一个数组,如果你返回一个元素的数组、一个数组或多个元素的,那就没有区别了

最新更新