How to find the number of HTML elements with a name that starts with a certain string in c#?
I'm not sure if the topic de开发者_运维问答scribes my problem very well but I am creating some HTML elements (textboxes) on the fly with jQuery and I never know how many I will create (it loops through a database). I then want to get all the elements in the code behind and perform some actions (insert them into another database).
I know I can use
string n = String.Format("{0}", Request.Form["hiddenField0"]).ToString();
To get the first textbox but what if Idon't know how many textboxes I have created and want them all? Their name starts with hiddenField plus an incrementing number.
Is there a way to loop through all elements that has a name that starts with a certain string?
Thanks in advance
var dictionary = Request.Form.Keys
.Cast<string>()
.Where(x => x.StartsWith("abc"))
.ToDictionary(x => x, x => Request.Form[x]);
Returns a dictionary containing the keys/values for all form elements that start with "abc".
Update: The poor OP is using .Net 2.0. So here is the old-school answer:
Dictionary<string, string> keys = new Dictionary<string, string>();
foreach (string key in request.Form.Keys)
{
if (key.StartsWith("abc"))
keys[key] = request.Form[key];
}
精彩评论