Problem?
How To Pass List Of Items In Query String from JavaScript And Fetch It In Code Behind In Asp.net.
What is Query String?
Query String is a part of the URL (Uniform Resource Locator) which is used to transfer data/value from one webpage to another webpage.
- Query String is one of the Client Side State Management Techniques.
- Ex: www.querystring.aspx?name=Vinod&place=Bangalore.
- Here,
- Question Mark (?) is separator, which separates query string from URL.
- name=Vinod , name is key for first parameter and Vinod is the value.
- Ampersand(&) is used when multiple parameters have to be sent. In above example it separates the second parameter place=Bangalore.
- Maximum Limit Of Query String Length,
- There is no limit actually to query string, but limit is imposed by web browsers and server software.
- Ex: Microsoft Internet Explorer there is limit of 2083 characters of URL length.
- When the value is exceeded it produces an error message in Internet Explorer.
- Situation,
- So when there is an situation where we have to pass more parameters and it exceeds browser character limit we can consider to use JSON Array.
Passing JSON Array from Javascript as Query String to Code Behind in Asp.net
Here I have taken an example of registration page where we have lot of parameters to pass to next registration confirmation page.
Javascript Code
Keys is an array
Pushing all parameters in <Key, Value> format in Keys array
- keys.push({
- firstName:”Vinod”,
- lastName: ”L”,
- mobileNo:”9999999999”,
- password:”Vinod@Csharpcorner”,
- dob:”01-01-1111”,
- cardType: ”Visa”,
- cardNumber:”XXXX-XXXX-XXXX-XXXX”,
- cardExpiry:”XX-XXXX”,
- cardHolder: “Vinod”
- })
Converting Keys array to JSON Format,check if data is not empty and passing it in the query string.
- if(JSON.stringify(keys) !== "[]") {
- window.location.href = "RegistrationConfirm.aspx?query=" + JSON.stringify(keys);
- }
Above query is the key and JSON.stringify(keys) is the value.
C# Codebehind Code
Namespace to be included for the deserialized JSON Object
- using System.Web.Script.Serialization;
- using Newtonsoft.Json.Linq;
- using Newtonsoft.Json;
Request Query String Data with Key name “query”
- var keys = Request.QueryString["query"];
Deserialize JSON Serialized Object to JSON Object
- dynamic key = JsonConvert.DeserializeObject(keys);
Fetching data one by one based on the Keys,
- string firstName = key[0]["firstName"].Value;
- string lastName = key[0]["lastName"].Value;
Similarly further parameter can be accessed based on the keys mentioned.