EliotE123
EliotE123

Reputation: 47

Passing Javascript objects to C#

I have retrieved data from my web form and put it into an object using Javascript on button_click. I have then attempted to use Ajax and JSON to pass the object to a method in my C# code.

Javascript:

$(document).ready(function () {
    $("#go").click(function () {
        $('#<%=gv_Rota.ClientID%>')
            .find('tr')
            .each(function (row) {
                $(this).find('select')
                    .each(function (col) {
                        $ctl = $(this)
                        if ($ctl.is('select')) { 
                            var shift = $ctl.val();
                            var day = row;
                            var wk = col + 1;
                            var objectitem = { ShiftId: shift, Day: day, Week: wk };
                            $.ajax({
                                url: '/Administration.aspx/StoreObject',
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify({ myObject: objectitem })
                            });
                        }
                    });
                });
            });
        });

C# behind:

[WebMethod]
public static void StoreObject(string[] myObject)
{

}

In the Javascript, you can see that it loops around a GridView and finds the selectedvalues from DropDownLists inside the GridView. Therefore, the Javascript is going to run multiple times, meaning multiple objectd are going to be passed.

How do I save all these objects passed to C# in rows of a DataTable, for example, which can then be used when I press a 'Save' button. Firstly, I am not too sure what goes in the StoreArray method, and secondly, I'm not sure what would be the best way to keep the DataTable for example (if that is what I store my objects in), after I press the 'Save' button and PostBack, as I am sure it would be reset due to this?

Upvotes: 3

Views: 674

Answers (1)

Eystein Bye
Eystein Bye

Reputation: 5126

Create a class in C# that reflects the object you have in your JavaScript

Something like this:

public class Item
    {
        public string Id { get; set; }
        public string Day { get; set; }
        public string Week { get; set; }
    }

Then expect that as you input

[WebMethod]
public static void StoreObject(Item myObject)
{

}

Edit:

If you want to save the items to a collection you can make a list of Items like this:

 private List<Item> myList = new List<Item>();

[WebMethod]
public void StoreObject(Item myObject)
{
    myList.Add(myObject);
}

NB: it can not be static for this to work. Im not sure that WebMethods support static methods. If not you need to make a asmx page to host the method See here

Upvotes: 4

Related Questions