Monday, December 28, 2009

Use POST instead of GET

Why do we use POST instead of GET?
GET shows lots of ugly names and values in url. Most browsers have some restrictions on the size of url string. The above 2 points make POST a better choice over GET.

We will quickly see, how can we convert our existing GETs to POSTs.

When a new page is to be called we will create a form dynamically, create hidden fields for all the values to be passed and submit it. The following script can help you in achieving this.
Assume that valuesToPost is a javascript array of objects which has fields Name and Value.

function PostIt(valuesToPost, targetUrl)
{
   var form = document.createElement("form");
   form.setAttribute("method", "post");
   form.setAttribute("action", targetUrl);
   for (var i=0; i<valuesToPost.length; i++)
   {
      var hiddenField = document.createElement("input");
      hiddenField.setAttribute("type", "hidden");
      hiddenField.setAttribute("name", valuesToPost[i].Name);
      hiddenField.setAttribute("value", valuesToPost[i].Value);
      form.appendChild(hiddenField);
   }
   document.body.appendChild(form);
   form.submit();
}

We can read these passed values from the page as follows. These dynamically posted values will be available only when IsPostback is false.
So on page_load, the following code can read these posted values.

if(!IsPostback)
{
   string id = GetPostedValue("Id");
   Dictionary<string, string> postedValues = GetPostedValues();
}

public string GetPostedValue(string key)
{
   return Request.Form[key];
}

public Dictionary<string, string> GetPostedValues()
{
   Dictionary<string, string> postedVals = new Dictionary<string, string>();
   foreach (string key in Request.Form.AllKeys)
      postedVals.Add(key, Request.Form[key]);
   return postedVals;
}

Now bye bye to ugly URLs.
Happy POSTing!!!

No comments:

Post a Comment