[英]string.contains(string) match whole word
在我看来,
@using(Html.BeginForm("Action", "Controller", FormMethod.Post)){
<div>
@Html.TextBox("text_1", " ")
@Html.TextBox("text_2", " ")
@if(Session["UserRole"].ToString() == "Manager"){
@Html.TextBox("anotherText_3", " ")
}
</div>
<button type="submit">Submit</button>
}
在我的控制器中
public ActionResult Action(FormCollection form){
if(!form.AllKeys.Contains("anotherText")){
ModelState.AddModelError("Error", "AnotherText is missing!");
}
}
我有一个表单并将其发布到我的方法中,在我的方法中,我想检查ID是否包含“ anotherText”的文本框,但是我使用.Contains()它始终给出false,这在我的formcollection中找不到...如何我可以这样做,以检查是否存在包含“ anotherText”的id的文本框?
搜索会失败是有道理的,因为它不完全匹配。
请尝试使用StartsWith
,以查看是否有任何键以您要查找的值开头。
if (!form.AllKeys.Any(x => x.StartsWith("anotherText")))
{
// add error
}
不像string.Contains
这将return true
,如果string
包含给定的子 ,你在这里做在检查是否AllKeys
(这是一个Collection)有任何Key
( 一个键- 集合的子项 ),这是string
"anotherText"
。
if(!form.AllKeys.Contains("anotherText"))
因此, 集合中的子项目是整个 string
本身,而不是substring
string
因此,您的AllKeys
必须真正包含与其匹配的确切string
:
"anotherText_2", //doesn't match
"anotherText_1", //doesn't match
"anotherText_3", //doesn't match
"anotherText" //matches
与Contains
在string
比较
string str = "anotherText_3";
str.Contains("anotherText"); //true, this contains "anotherText"
因此,您应该检查Any
一个Keys
是否具有"anotherText"
:
if (!form.AllKeys.Any(x => x.Contains("anotherText")))
{
// add error
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.