Search code examples
c#asp.net-mvcvalidationasp.net-mvc-4formcollection

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?


Solution

  • 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.

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