|
Written by
|
|
Tuesday, 16 February 2010 12:41 |
// We were having a problem where it was not possible to detect the difference between a value being passed with no value and the value not being passed at all. This was a problem because we have a singe update page to handle most of the database saves; it would loop through all the possible values of a data object setting them based on what was passed in the form. If a column was not present in the original form it would be set to NULL by the update page. The work around was to place these values in the original form as hidden elements; this meant that whenever we added a column it had to be added to the form(s). This was obviously not a tenable solution so I came up with the following method of requesting a value from a POST or GET.
#region Private Properties
string[] _formKeys;
string[] _queryStringKeys;
#endregion
#region Web Page Properties
/// A list of keys found in Request.Form
protected string[] FormKeys
{
get
{
if (this._formKeys == null)
this._formKeys = Request.Form.AllKeys;
return this._formKeys;
}
}
/// A list of keys found in Request.QueryString
protected string[] QueryStringKeys
{
get
{
if (this._queryStringKeys == null)
this._queryStringKeys = Request.QueryString.AllKeys;
return this._queryStringKeys;
}
}
#endregion
#region public methods
///Grabs parameter from Form or Query String. Never returns NULL.
/// The name of the parameter to be pulled
/// Value of parameter. Returns String.Empty if no value or parameter found.
protected string requestParam(string paramName)
{
string result = requestParam(paramName, false);
return (result == null) ? String.Empty : result.Trim();
}
///Grabs parameter from Form or Query String.
/// The name of the parameter to be pulled
/// Will return NULL if parameter was not passed in the form or query string. If false an empty string will be returned.
/// Value of parameter. Returns String.Empty parameter found but has no value.
///
protected string requestParam(string paramName, bool returnNullIfParamNotFound)
{
string result = String.Empty;
if (Context.Request.Form.Count != 0)
{
result = Convert.ToString(Context.Request.Form[paramName]);
}
if (Context.Request.QueryString.Count != 0 && (result == String.Empty || result == null))
{
result = Convert.ToString(Context.Request.QueryString[paramName]);
}
if (result == null && returnNullIfParamNotFound)
{
// check the form keys
for (int x = 0; x < this.FormKeys.Length; x++)
if (string.Equals(paramName, this.FormKeys[x], StringComparison.OrdinalIgnoreCase))
return string.Empty; //doing a return to skip the rest
// check the query string keys
for (int x = 0; x < this.QueryStringKeys.Length; x++)
if (string.Equals(paramName, this.QueryStringKeys[x], StringComparison.OrdinalIgnoreCase))
return string.Empty; //doing a return to skip the rest
}
return result;
}
#endregion
 Read more: |