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.

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.