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?
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
}
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"
.
if(!form.AllKeys.Contains("anotherText"))
Consequently, your sub-item in the Collection is the entire string
itself, not the substring
of the string
Thus your AllKeys
must really contain an exact string
that matches it:
"anotherText_2", //doesn't match
"anotherText_1", //doesn't match
"anotherText_3", //doesn't match
"anotherText" //matches
Compare with Contains
in a string
string str = "anotherText_3";
str.Contains("anotherText"); //true, this contains "anotherText"
Thus, you should rather check if Any
of the Keys
have "anotherText"
:
if (!form.AllKeys.Any(x => x.Contains("anotherText")))
{
// add error
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.