How to find the number of HTML elements with a name that starts with a specific line in C #?

I'm not sure the topic describes my problem very well, but I create some HTML elements (text fields) on the fly using jQuery, and I never know how much I will create (it scrolls through the database). Then I want to get all the elements in the code and perform some actions (paste them into another database).

I know I can use

string n = String.Format("{0}", Request.Form["hiddenField0"]).ToString();

To get the first text field, but what if I don’t know how many text fields I created and want them all? Their name begins with hiddenField plus the plus number.

Is there a way to iterate over all elements with a name that starts with a specific string?

Thanks in advance

+3
source share
1 answer
var dictionary = Request.Form.Keys
     .Cast<string>()
     .Where(x => x.StartsWith("abc"))
     .ToDictionary(x => x, x => Request.Form[x]);

Returns a dictionary containing keys / values ​​for all form elements starting with "abc".

Update: Bad OP uses .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];
}
+8
source

Source: https://habr.com/ru/post/1769677/


All Articles