2

I want to pass bitArray from my javascript file to my method in webApi

I create bitArray as below in my javascript file

 var myBits = new BitArray(2);
 myBits.setAt(1,false);
 myBits.setAt(2,true);

Then i call method in webApi which is as below

 public int ConvertArray(BitArray a)
    {
        //some logic
    }

I use Breeze to pass data to webapi, so i try to pass data as below

var query = EntityQuery.from("ConvertArray")
                  .withParameters({ a: myBits });
        manager1.executeQuery(query);

But when i put breakpoint in my webapi method i get blank data. But when i put breakpoint in javascript while i am passing data is get 2 records or i should say 2 bitArrays.

Does someone know how to pass bitArray to webapi?

Update 1

Here is how my bitarray looks like in my code BitArray

James
  • 1,827
  • 5
  • 39
  • 69

2 Answers2

2

One possibility is to store the BitArray as a bit string before sending it to the server then convert it to a C# BitArray once the string reaches the server side.

Javascript

BitArray.prototype.toString = function() {
    this.m_bits.join('');
};

Use this method to make an array like [ 1, 0, 1, 0 ] change to the string 1010.

C#

BitArray a = new BitArray(bitString.Select(c => c == '1' ? true : false).ToArray());
David Sherret
  • 101,669
  • 28
  • 188
  • 178
  • I get undefined when i use prototype.toString – James Sep 03 '14 at 22:20
  • @Happy you need to define `toString` as a function of `BitArray` that returns the underlying number array as string of `1`s and `0`s. The above is an example and you would normally use it by doing something like `myBits.toString()`. Maybe you could post the code for `BitArray`? – David Sherret Sep 04 '14 at 02:07
  • I got this idea of bitarray from this http://stackoverflow.com/questions/6972717/how-do-i-create-bit-array-in-javascript – James Sep 04 '14 at 06:38
  • It worked when i used myBits.toString. Many thanks. But can you explain me about code new BitArray(bitString.Select(c => c == '1' ? true : false).ToArray()); I didnt understood much – James Sep 04 '14 at 07:17
  • Pass in `myBits.toString()` to the server and change the `ConvertArray` function header to be `public int ConvertArray(string bitString)` to accept the string. Once you have that string you can plug in that c# code above to get a BitArray from the string. What that code does is loops over each character in the string and creates a new boolean array where `1` => `true` and `0` => `false`. It then passes this array to the BitArray constructor which creates a new BitArray based on the boolean array. – David Sherret Sep 04 '14 at 13:41
1

Breeze sends the query parameters in the URL, so they need to be serialized to a string. Your BitArray prototype needs to have a toString() method that serializes the bits in a way that your server can understand.

Steve Schmitt
  • 3,124
  • 12
  • 14