Asp – Searching for controls in Request.Form / Parsing a NameValueCollection

.netasp.net

I am searching for control names using Request.Form.

Of course I know you can can iterate around all values using AllKeys, and you can do Form["controlName"] as well.

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

1)Getting a subset of controls in the collection whos name start with a certain prefix
2) Search for control names that match a pattern, as you would do with a regular expression.

But there is no way I can see to do stuff like this.

N.B I know how to use FindControl for ASP.NET controls but these are standard HTML.

Best Solution

If you are using C#3 you can use LINQ and extension methods to achieve this in a very nice way. First you need to create an extension method devised 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, say you had a form like this:

<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 could do this in your codebehind:

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));
    }
}

Which would output:

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