views:

32

answers:

2

I have an array of javascript objects and I want to press a submit button and 'send' them much like I can access a textbox or listbox's members - ie. the page posts back and I can put some code in the button's submit method. Is there a way of doing this? Or do I have to put them into a control?

+1  A: 

On the button's submit method, you need to serialize your array of JavaScript objects and assign it to a hidden input. On the server-side you then get that JSON string out of the input and do something with it (e.g. deserialize it).

To serialize, first add a ScriptManager to the page:

<asp:ScriptManager runat="server" />

Then you can run JavaScript like this:

<script type="text/javascript">
    window.onload = function () {
        var value = {
            a: "a",
            b: 123,
            c: [
                "c1",
                "c2"],
            d: {
                d1: "d1",
                d2: "d2"
            }
        };
        var result = Sys.Serialization.JavaScriptSerializer.serialize(value);
        alert(result);
    }
</script>
langsamu
Superb, how do I serialize it using Javascript?
SLC
Using Sys.Serialization.JavaScriptSerializer from ASP.NET AJAX as linked in my answer and noted by bugventure.Added example above.
langsamu
+1  A: 

If you are using MS AJAX, you can use the Sys.Serialization.JavaScriptSerializer object to serialize your javascript object to a string.

bugventure