How To: Get the Value of a Control Without an instance of the Control

On my quest to write one blog a day in July, here is my first post regarding how to get the value of a control without the control instance.  This can be very helpful for HTTP pipeline development or when the value of the control is needed very early in the page lifecycle.

public static string GetControlValueFromRequest(string controlId)
{            
    string requestValue = null;
    controlId = controlId.ToLower();
    HttpRequest req = HttpContext.Current.Request;
    string eventTarget = req.Form["__EVENTTARGET"] ?? string.Empty;
    if (eventTarget.ToLower().EndsWith(controlId))
    {
        requestValue = req.Form["__EVENTARGUMENT"];                
    }
    if (string.IsNullOrEmpty(requestValue))
    {
        foreach (string id in req.Form.AllKeys)
        {
            if (id.ToLower().EndsWith(controlId))
            {
                requestValue = req[id];
            }
        }
    }            
    return requestValue;
}
del.icio.us Tags: , , , ,
Published Sunday, July 01, 2007 11:26 PM by Palermo4
Filed under: , , ,

Comments

# re: How To: Get the Value of a Control Without an instance of the Control

Monday, July 02, 2007 10:38 AM by David L. Penton

If there are two controls named 'mail' and 'email' if you are searching using

   .EndsWith( controlId )

you could introduce the wrong value.  Wouldn't something like (not tested)

   .EndsWith( this.Page.IdSeparator + controlId )

be better?  The idea would be to try to prevent as many false positives as possible...

# re: How To: Get the Value of a Control Without an instance of the Control

Monday, July 02, 2007 12:15 PM by William

That's really interesting, but where can I found more information on how this works "behind the scenes?"

# re: How To: Get the Value of a Control Without an instance of the Control

Tuesday, July 03, 2007 2:19 PM by Gareth Brown

Now that is cool, but this line:

string eventTarget = req.Form["__EVENTTARGET"] ?? string.Empty;

is even cooler...how have I ever missed ??, so useful.

Thanks

# re: How To: Get the Value of a Control Without an instance of the Control

Tuesday, July 03, 2007 5:54 PM by Palermo4

David,

I agree.  I made some changes to the method, and I will post it to the blog soon!  Thanks for your insight!

# re: How To: Get the Value of a Control Without an instance of the Control

Tuesday, July 03, 2007 6:25 PM by Palermo4

Gareth,

I agree, it took me a year after 2.0 came out before I discovered that one!

# Revision: Get the Value of a Control Without an Instance of the Control

Friday, July 20, 2007 3:15 PM by Palermo4

On an earlier post, I provided code that would retrieve the value of a control from the HTTP post without

Leave a Comment

(required) 
(required) 
(optional)
(required)