Retrieving Query String Value Through JavaScript
In World Wide Web, a query string is a part of a URL that contains data to be passed to web applications (http://en.wikipedia.org/wiki/Query_string).
The query string is composed of a series of field – value pair. Below is the pattern of query string:
The query string is composed of a series of field – value pair. Below is the pattern of query string:
field1=value1&field2=value2&field3=value3
An URL that contains query string can be depicted as follow:
The URL and query string separated by a question mark (?). Query string consist of two parts (field and value), and each of pair separated by ampersand (&). So the example above consists of two query strings which are name and type with value of each field ‘alma’ and ‘user’ respectively.
http://test.com/tag?name=alma&role=user
The URL and query string separated by a question mark (?). Query string consist of two parts (field and value), and each of pair separated by ampersand (&). So the example above consists of two query strings which are name and type with value of each field ‘alma’ and ‘user’ respectively.
We can retrieve the query string values programmatically and used that values. Now we will learn how to get the query string values in ASP.NET and Javascript.
Retrieving Query Strings in ASP.NET
Retrieving query strings in ASP.NET is quite simple, what we need is just the following line of code:
or
Retrieving query strings in ASP.NET is quite simple, what we need is just the following line of code:
Page.Request.QueryString[queryStringField];
or
Page.Request.QueryString[indexOfQueryString];
So If we need to retrieve the value of name field from this URL:
Just do this inside of your ASP.NET code: Page.Request.QueryString["name"] or Page.Request.QueryString[0]. Lets look at how it work in simple source of code (Test.aspx):
http://test.com/tag?name=alma&role=user
Just do this inside of your ASP.NET code: Page.Request.QueryString["name"] or Page.Request.QueryString[0]. Lets look at how it work in simple source of code (Test.aspx):
- <%@ Page Language=”C#” %>
<html>
<head>
<title>Query Strings in ASP.NET: Page 1</title>
<script language=”C#” runat=”server”>
void GetQrStr(object sender, EventArgs e)
{
// change the Response.Redirect parameter with your own location.
Page.Response.Redirect(“/…/Test2.aspx?name=alma&role=user”);
}
</script>
</head>
<body>
<form runat=”server”>
<asp:Button id=”btn” onclick=”GetQrStr” text=”Test Query Strings” runat=”server” />
</form>
</body>
</html>
Test.aspx will produce a button that will redirect to Test2.aspx when it clicked. This is code for Test2.aspx:
- <%@ Page Language=”C#”%>
<html>
<head>
<title>Query Strings in ASP.NET: Page 2</title>
<script language=”C#” runat=”server”>
</script>
</head>
<body>
<%
// retrieves query string values
string name = Page.Request.QueryString["name"];
string role = Page.Request.QueryString["role"];
<head>
<title>Query Strings in ASP.NET: Page 2</title>
<script language=”C#” runat=”server”>
</script>
</head>
<body>
<%
// retrieves query string values
string name = Page.Request.QueryString["name"];
string role = Page.Request.QueryString["role"];
Page.Response.Write(“<h1>Name: “+name+”, Role: “+role+”</h1>”);
%>
</body>
</html>
%>
</body>
</html>
In Test2.aspx we can get the values of ‘name’ and ‘role’ query strings then use both values as we need.
Retrieving Query Strings in Javascript
Javascript can be used for retrieves query string values too. We need the following code to get query string pairs (field & value) using Javascript:
Javascript can be used for retrieves query string values too. We need the following code to get query string pairs (field & value) using Javascript:
window.location.search
The above code will return string started with ampersand in the URL (ampersand included). So if we run the above code against the following URL:http://localhost:8088/postings/QrStr/testjs2.htm?name=alma&role=user
The return value is ?name=alma&role=user
The return value is ?name=alma&role=user
To understand the concept better I have write two simple HTML pages that show how to get query string values using Javascript. This is the first file (testqrstr.htm):
- <html>
<head>
<title>Test Query Strings: Page 1</title>
<script lang=”javascript” type=”text/javascript”>
function testQueryStrings()
{
// change the window.location with your own.
window.location = “/…/testjs2.htm?name=alma&role=user”;
}
</script>
</head>
<body>
<input type=”button” id=”btn” value=”Test Query Strings” onclick=”testQueryStrings()” />
</body>
</html>
The output produced by testjs.htm is similar like the output of Test.aspx, when we click the button it will bring us to testjs2.htm (of course with the specified query strings!). Here testjs.htm:
<html>
<head>
<title>Test Query Strings: Page 2</title>
<script lang=”javascript” type=”text/javascript”>
var qrStr = window.location.search;
var spQrStr = qrStr.substring(1);
var arrQrStr = new Array();
// splits each of pair
var arr = spQrStr.split(’&’);
</script>
</head>
<body>
</body>
</html>
<head>
<title>Test Query Strings: Page 2</title>
<script lang=”javascript” type=”text/javascript”>
var qrStr = window.location.search;
var spQrStr = qrStr.substring(1);
var arrQrStr = new Array();
// splits each of pair
var arr = spQrStr.split(’&’);
for (var i=0;i<arr.length;i++){
// splits each of field-value pair
var index = arr[i].indexOf(’=');
var key = arr[i].substring(0,index);
var val = arr[i].substring(index+1);
// splits each of field-value pair
var index = arr[i].indexOf(’=');
var key = arr[i].substring(0,index);
var val = arr[i].substring(index+1);
// saves each of field-value pair in an array variable
arrQrStr[key] = val;
}
arrQrStr[key] = val;
}
alert(arrQrStr["Location"]);
</script>
</head>
<body>
</body>
</html>
Calling ASP.Net validators from JavaScript
There are situations when we want to call Asp.net validatiors form JavaScript. One such situation is when we want to close a pop up window on button click using window.close(). But before closing the window using JavaScript, we want to validate the data written in the controls of the window.
It possible to call Asp.net validators from JavaScript. The following code shows a portion of asp.net page which includes one standard .net required field validator and one regular expression validator.
<table>
<tr>
<td><asp:Label ID=”lbl1″ runat=”server” Text=”Please enter a digit”></asp:Label></td>
<td><asp:TextBox ID=”txtbox1″ runat=”server”></asp:TextBox></td>
<td><asp:RequiredFieldValidator ID=”valReq” ControlToValidate=”txtbox1″ runat=”server” ErrorMessage=”*” Display=”Dynamic”>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID=”valreg” ControlToValidate=”txtbox1″ runat=”server” ErrorMessage=”Not valid character” ValidationExpression=”[0-9]“>
</asp:RegularExpressionValidator></td>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID=”valreg” ControlToValidate=”txtbox1″ runat=”server” ErrorMessage=”Not valid character” ValidationExpression=”[0-9]“>
</asp:RegularExpressionValidator></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID=”btn1″ runat=”server” Text=”Submit” OnClientClick=”performCheck()”/></td> <td></td>
<td><asp:Button ID=”btn1″ runat=”server” Text=”Submit” OnClientClick=”performCheck()”/></td> <td></td>
</tr>
</table>
In design mode, it looks as below
Now we want to make sure that .net validators get fired up on “Submit” button click before closing the window using javascript window.close(). In our example, we have a text box where we expect a single digit before closing the window.
All we have to do to fire up .net validators is to call “Page_ClientValidate()” function. The following JavaScript code shows how “Page_ClientValidate()” function can be used before closeing window.
<script type=”text/javascript” language=”javascript”>
function performCheck()
{
{
if(Page_ClientValidate())
{
{
window.close();
}
}
</script>
</script>
Now, if the Submit button is clicked leaving the text box empty, the required field validator will fire up as shown in the below screen shot.
If any thing is written in other than a single digit, we will get the following output.
How about Calling any specific validator rather than all?
Well, this can be done as well. In this case we need to provide a ValidationGroup name for the validator and pass the validator group name to Page_ClientValidate() function as parameter. The following code segment shows a group name is provided for the required field validator and passed it to Page_ClientValidate() function. In this case, only required field validatior will be fired up and not the regular expression validator.
<table>
<tr>
<td><asp:Label ID=”lbl1″ runat=”server” Text=”Please enter a digit”></asp:Label></td>
<td><asp:TextBox ID=”txtbox1″ runat=”server”></asp:TextBox></td>
<td><asp:RequiredFieldValidator ID=”valReq” ControlToValidate=”txtbox1″ runat=”server”
ErrorMessage=”*” ValidationGroup=”Required” Display=”Dynamic”>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID=”valreg” ControlToValidate=”txtbox1″ runat=”server”
ErrorMessage=”Not valid character” ValidationExpression=”[0-9]“ValidationGroup=”RegExpression”>
</asp:RegularExpressionValidator></td>
<td><asp:TextBox ID=”txtbox1″ runat=”server”></asp:TextBox></td>
<td><asp:RequiredFieldValidator ID=”valReq” ControlToValidate=”txtbox1″ runat=”server”
ErrorMessage=”*” ValidationGroup=”Required” Display=”Dynamic”>
</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID=”valreg” ControlToValidate=”txtbox1″ runat=”server”
ErrorMessage=”Not valid character” ValidationExpression=”[0-9]“ValidationGroup=”RegExpression”>
</asp:RegularExpressionValidator></td>
</tr>
<tr>
<td></td>
<td><asp:Button ID=”btn1″ runat=”server” Text=”Submit” OnClientClick=”performCheck()”/></td>
<td></td>
<td><asp:Button ID=”btn1″ runat=”server” Text=”Submit” OnClientClick=”performCheck()”/></td>
<td></td>
</tr>
</table>
<script type=”text/javascript” language=”javascript”>
function performCheck()
{
function performCheck()
{
if(Page_ClientValidate(“Required”))
{
{
window.close();
}
}
</script>
</script>
Advantage
By using standard asp.net validators for validation, we don’t have to write JavaScript code to do the validation. This can minimize the development time to a great extent.
No comments:
Post a Comment