Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing variables from Javascript to C# via forms?

I have an array which I am storing inside an <input type="hidden">. Here is my code.

Javascript:

var trees;

// called when the body loads
function BodyOnLoad()
{
  trees = document.getElementById("trees");
  trees.value = new Array();
}

// this is what isn't working
function AddTree()
{
  var i = trees.value.length;

  trees.value[i] = new Array();
  /***/
  trees.value[i]["branches"] = 5;
  trees.value[i]["trunk"]    = 0;
}

HTML: <input type="hidden" name="trees" id="trees" />

In C#, Request.Form["trees"] is not an array. What am I doing wrong?


2 Answers

The HTML form post won't preserve a javascript object (in this case an Array). You should look at converting your Array to JSON and passing that in the form if you need to preserve the array object.

Include this script (JSON2) in your page: JSON2

var treesArray;

// called when the body loads
function BodyOnLoad()
{
  treesArray = new Array();
}

function AddTree()
{
  var tree = new Array();

  //branches      
  tree[0] = "5";

  //trunk      
  tree[1] = "0";

  //name
  tree[2] = "Elm";

  treesArray[treesArray.length] = tree;
  document.getElementById("trees").value = JSON.stringify(treesArray);
}

Then on the server side you will need to convert the JSON to a C# Array using something like this:

Add reference to JavaScriptSerializer from System.Web.Extensions.dll (.NET 3.5 SP1)

JavaScriptSerializer serializer = new JavaScriptSerializer();
string[][] trees = serializer.Deserialize<string[][]>(Request.Form["trees"]);

for(int i = 0; i < trees.Length; i++)
{
    Console.WriteLine("Branches:" + trees[i][0]);
    Console.WriteLine("Trunk:" + trees[i][1]);
    Console.WriteLine("Name:" + trees[i][2]);
}
like image 124
AVH Avatar answered Mar 11 '26 14:03

AVH


You cannot set the value of an input element to an array in javascript.

You can only set strings as value of input elements.

If you want to send multiple values to the server, you must concatenate mutiple strings, and use a separator, like a pipe '|' or comma ','... and then on the server you need to split the string, by using that separator.

like image 23
Miguel Angelo Avatar answered Mar 11 '26 13:03

Miguel Angelo