Finding Controls in Request.Form / Parsing NameValueCollection

I am looking for management names using Request.Form.

Of course, I know that you can iterate over all values ​​using AllKeys, and you can also use Form ["controlName"].

However, some of my control names are dynamic, and it would be useful to be able to do things like:

1) Getting a subset of the controls in the collection name starts with a specific prefix 2) Find the control names that match the pattern, as you would with a regular expression.

But I do not see how to do it.

NB I know how to use FindControl controls for ASP.NET, but this is standard HTML.

+3
source share
3 answers

If you use C # 3, you can use LINQ and extension methods to achieve this very nicely. First you need to create an extension method developed by Bryan Watts in this thread :

public static IEnumerable<KeyValuePair<string, string>> ToPairs(this NameValueCollection collection)
{
    if (collection == null)
    {
        throw new ArgumentNullException("collection");
    }
    return collection.Cast<string>().Select(key => new KeyValuePair<string, string>(key, collection[key]));
}

Now, let's say you had this form:

<form id="form1" runat="server">
<div>
    <input type="text" name="XXX_Name" value="Harold Pinter" />
    <input type="text" name="XXX_Email" value="harold@example.com" />
    <input type="text" name="XXX_Phone" value="1234 5454 5454" />

    <input type="text" name="YYY_Name" value="AN. Other" />
    <input type="text" name="YYY_Email" value="another@example.com" />
    <input type="text" name="YYY_Phone" value="8383 3434 3434" />

    <input type="submit" value="submit button" />
</div>
</form>

You can do this in your code:

protected void Page_Load(object sender, EventArgs e)
{
    var data = Request.Form.ToPairs().Where(k => k.Key.StartsWith("XXX_"));

    foreach (var item in data)
    {
        Response.Write(String.Format("{0} = '{1}', ", item.Key, item.Value));
    }
}

What will be output:

XXX_Name = 'Harold Pinter'
XXX_Email = 'harold@example.com'
XXX_Phone = '1234 5454 5454'
+7
source

Just loop around Request.Form.AllKeys, make any template you want with the key name, and then if it matches, you can print the value.

foreach (var key in Request.Form.AllKeys)
{
    if (key.StartsWith("abc"))
    {
        var value = Request.Form[key];
        Do_Something(key, value);
    }
}
0
source

Do not use foreach (the var key in Request.Form.AllKeys). I have a defect right in front of me where the key is not evaluating anything. Use the string key in Request.Form.AllKeys for security.

0
source

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


All Articles