簡體   English   中英

string.contains(string)匹配整個單詞

[英]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

Containsstring比較

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM