Revision: Get the Value of a Control Without an Instance of the Control
On an earlier post, I provided code that would retrieve the value of a control from the HTTP post without the need for an instance of the control. With good feedback, I made some modifications as follows:
public static string GetControlValueFromRequest(string controlId) { if (controlId == null) throw new ArgumentNullException("controlId"); string requestValue = null; HttpRequest req = HttpContext.Current.Request; string eventTarget = req.Form["__EVENTTARGET"] ?? string.Empty; if (eventTarget.Equals(controlId, StringComparison.InvariantCultureIgnoreCase)) { requestValue = req.Form["__EVENTARGUMENT"]; } if (string.IsNullOrEmpty(requestValue)) { foreach (string id in req.Form.AllKeys) { if (controlId.Equals(GetFriendlyControlId(id), StringComparison.InvariantCultureIgnoreCase)) { requestValue = req[id]; break; } } } return requestValue; }If the foreach statement above, I call another helper method to return the "friendly" control id for comparison. This revision validates the controlId argument and is more efficient with string comparisons.