List Of Items In Query String From JavaScript And Fetch It In Code Behind In ASP.NET

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 the 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 a situation where we have to pass more parameters and it exceeds browser character limit we can consider using 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

  1. var keys = [];  

Pushing all parameters in <Key, Value> format in Keys array,

  1. keys.push({  
  2.                 firstName:”Vinod”,  
  3.  lastName: ”L”,  
  4.  mobileNo:”9999999999”,  
  5.  password:”Vinod@Csharpcorner”,  
  6.  dob:”01-01-1111”,  
  7.  cardType: ”Visa”,  
  8.  cardNumber:”XXXX-XXXX-XXXX-XXXX”,  
  9.  cardExpiry:”XX-XXXX”,  
  10.  cardHolder: “Vinod”  
  11.             })  

Converting Keys array to JSON Format,check if data is not empty and passing it in the query string.

  1.  if(JSON.stringify(keys) !== "[]") {  
  2.       window.location.href = "RegistrationConfirm.aspx?query=" + JSON.stringify(keys);  
  3. }  

Above query is the key and JSON.stringify(keys) is the value.

C# Codebehind Code

Namespace to be included for the deserialize JSON Object, 

  1. using System.Web.Script.Serialization;  
  2. using Newtonsoft.Json.Linq;  
  3. using Newtonsoft.Json;  

Request Query String Data with Key name “query”

  1. var keys = Request.QueryString["query"];  

Deserialize JSON Serialized Object to JSON Object

  1. dynamic key = JsonConvert.DeserializeObject(keys);  

Fetching data one by one based on the Keys

  1. string  firstName = key[0]["firstName"].Value;  
  2. string lastName = key[0]["lastName"].Value;  

Similarly further parameter can be accessed based on the keys mentioned.


Similar Articles