Tuesday, August 9, 2016

Get Querystring Value from server side and from client side using Javascript

With querystring we can pass values from one page to another. Any number of values can be
passed via url but for sending large amounts of data beyond 100KB it cannot be used.

C# code (.aspx.cs) :


string qs = Request.QueryString["id"];

There might be scenario where querystring value is required in client side.
Javascript code for that is as follows:

Javascript  Code:


<script language="javascript">
        function getquerystringByName(name) {
            name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
            var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
         results = regex.exec(location.search);
            return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
        }
</script>

Suppose we want to get the querystring value and set to an input control on body's onload 
we can call Javascript function as follows :

<script language="javascript">
  function setValue() {
         var val = getquerystringByName('id');
         if (val != null) {
             if (val != '')
                 document.getElementById('getValue').value = val;
         }

        }

</script>


<body onload="javascript:setValue();">
    <form id="form1" runat="server">
    <div>
    <input id="getValue" type="text" />
    </div>
    </form>
</body>

No comments:

Post a Comment