【问题标题】:string.contains(string) match whole wordstring.contains(string) 匹配整个单词
【发布时间】:2016-01-28 05:04:41
【问题描述】:

在我看来,

@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的文本框是否存在?

【问题讨论】:

    标签: c# asp.net-mvc validation asp.net-mvc-4 formcollection


    【解决方案1】:

    搜索失败是有道理的,因为它不是完全匹配。

    尝试改用StartsWith,看看是否有任何键以您要查找的值开头。

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

    【讨论】:

      【解决方案2】:

      string.Contains 不同,如果string 包含给定的子字符串,则return true,您在这里所做的是检查AllKeys(这是一个集合) 有任何Key单个键 - 集合子项)是@987654326 @"anotherText".

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

      因此,集合中的子项整个string本身,而不是@987654331的substring @

      因此,您的 AllKeys 必须确实包含与其匹配的确切 string

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

      string 中的Contains 比较

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

      因此,您应该检查Keys 中的Any 是否有"anotherText"

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

      【讨论】:

        猜你喜欢
        • 2012-03-29
        • 2012-01-26
        • 2012-06-22
        • 2014-08-17
        • 1970-01-01
        • 1970-01-01
        • 2011-09-11
        • 1970-01-01
        相关资源
        最近更新 更多