What's the best way to extract multiple fields from an asp.net form into a list or C # array ready for processing?

I need to extract multiple text / dropdowns from an asp.net form and a format suitable for sending to a recipient via email.

What is the best way to read these fields without having to hardcode each element like:

item1 = InputField1.Text; 
item2 = InputField2.Text; 

      

I will have about 10 or 20 items in the same input form.

0


source to share


2 answers


@Chris gave you the basic idea - copy from the Request.Form collection. I would suggest to make this easier, you give the input names that you can easily detect from other fields on the page, some of which can be placed there for you. Maybe use a naming scheme like "Email.FirstName", "Email.LastName", "Email.Address", then you can:

   foreach (string key in Request.Form.Keys)
   {
        if (key.StartsWith("Email."))
        {
           ...Process this key...
        }
   }

      



Note. If the page uses MasterPage, your validation should account for the account in the framework.

+1


source


Not sure why you are trying this - without further information it seems that you are probably using an approach that is not optimal, but I digress. Form field values ​​are also available through the Request.Form collection, which is a NameValueCollection if I remember. You can access it like this:

foreach (string key in Request.Form.Keys) {
    string value = Request.Form[key];
    // format and use value here
}

      



If you need to format specific fields based on the field and data type, you can make a copy in the dictionary like this:

Dictionary<string, object> values = new Dictionary<string, object>();

foreach (string key in Request.Form.Keys) {
    if (key.Equals("SpecialFieldName")) {
        // for example, parse an int
        values.Add(key, int.parse(Request.Form[key]));
    } else {
        // no special formatting required
        values.Add(key, Request.Form[key]);
    }
}

      

0


source







All Articles