3

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.

AJM
  • 32,054
  • 48
  • 155
  • 243

3 Answers3

7

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'
Community
  • 1
  • 1
Dan Diplo
  • 25,076
  • 4
  • 67
  • 89
0

Just loop through Request.Form.AllKeys, do whatever pattern you want on the key name, then if it matches you can pull the value out.

foreach (var key in Request.Form.AllKeys)
{
    if (key.StartsWith("abc"))
    {
        var value = Request.Form[key];
        Do_Something(key, value);
    }
}
David
  • 34,223
  • 3
  • 62
  • 80
0

Don't use foreach (var key in Request.Form.AllKeys). I have a defect right in front of me where key isn't evaluating to anything. Use string key in Request.Form.AllKeys to be safe.

Aaron
  • 1