Pre Populate form field based on URL

Discussion in 'C#' started by hershel, Nov 9, 2011.

  1. #1
    Hi i have the following URL:

    www.mysite.com/product.aspx?PID=1000

    I want to pre-populate a form field with the "PID" value in the URL -

    I have tried using:

    <input type="text" id="PID" value="<%=Request.QueryString("PID")%>">

    but it does not work.

    Can anyone help?

    Thanks
     
    hershel, Nov 9, 2011 IP
  2. DaveCS

    DaveCS Peon

    Messages:
    18
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You can do several things.
    1. Catch the query string in the page_load event like so.

    If Request.QueryString.Count > 0 Then
                Dim strQuery As String = Request.QueryString("PID").ToString
                If Not String.IsNullOrEmpty(strQuery) And strQuery.Contains("PID") Then
                      txtPID.Text=strQuery
                End If
            End If
    Code (markup):
    You can get the query string with javascript and call the function in the bodyonload
    hacky badly named variables but works
    
    <script type="text/javascript"> 
             function display()
     {              var tabvalueTest = getQueryVariable("PID");
                  if (tabvalueTest == 'undefined')
     {                 
     return  
                }  
                var tabvalue = getQueryVariable("PID"); 
                 if (tabvalue != "") 
    {                   document.getElementById('txtPID').value = tabvalue; //some textbox field 
                 }  
                       }  
        </script> <script type="text/javascript">  
       function getQueryVariable(variable)
     {         var query = window.location.search.substring(1);
             var vars = query.split("&"); 
            for (var i = 0; i < vars.length; i++)
     {             var pair = vars[i].split("="); 
                if (pair[0] == variable) 
    {                 return pair[1];  
               }      
       }    
     }  
    </script>
    Code (markup):
    then
    
    <body onload="display()">
    Code (markup):
    You can also use url rewriting and just throw a "PID" number at the page and have it add a variable during load.
     
    DaveCS, Nov 23, 2011 IP