简体   繁体   English

string.contains(string)匹配整个单词

[英]string.contains(string) match whole word

In my view, 在我看来,

@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>
}

In my controller, 在我的控制器中

public ActionResult Action(FormCollection form){
    if(!form.AllKeys.Contains("anotherText")){
        ModelState.AddModelError("Error", "AnotherText is missing!");
    }
}

I have a form and post to my method, in my method i want to check if a textbox with id that containing "anotherText", but i use .Contains() it always give false which is not found in my formcollection...How can i do so that it check if the textbox of id containing "anotherText" is existed? 我有一个表单并将其发布到我的方法中,在我的方法中,我想检查ID是否包含“ anotherText”的文本框,但是我使用.Contains()它始终给出false,这在我的formcollection中找不到...如何我可以这样做,以检查是否存在包含“ anotherText”的id的文本框?

It makes sense that the search would fail, since it's not an exact match. 搜索会失败是有道理的,因为它不完全匹配。

Try using StartsWith instead, to see if any key starts with the value you're looking for. 请尝试使用StartsWith ,以查看是否有任何键以您要查找的值开头。

if (!form.AllKeys.Any(x => x.StartsWith("anotherText")))
{
    // add error
}

Unlike string.Contains which will return true if the string contains the given substring , what you did here is checking if in the AllKeys (which is a Collection ) there is any Key (a single key - the sub-item of the Collection ) which is of the string "anotherText" . 不像string.Contains这将return true ,如果string包含给定的 ,你在这里做在检查是否AllKeys (这是一个Collection)有任何Key一个键- 集合子项 ),这是string "anotherText"

if(!form.AllKeys.Contains("anotherText"))

Consequently, your sub-item in the Collection is the entire string itself, not the substring of the string 因此, 集合中的子项目整个 string本身,而不是substring string

Thus your AllKeys must really contain an exact string that matches it: 因此,您的AllKeys必须真正包含与其匹配的确切string

"anotherText_2", //doesn't match
"anotherText_1", //doesn't match
"anotherText_3", //doesn't match
"anotherText" //matches

Compare with Contains in a string Containsstring比较

string str = "anotherText_3";
str.Contains("anotherText"); //true, this contains "anotherText"

Thus, you should rather check if Any of the Keys have "anotherText" : 因此,您应该检查Any一个Keys是否具有"anotherText"

if (!form.AllKeys.Any(x => x.Contains("anotherText")))
{
    // add error
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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