Mehaini
Mehaini

Reputation: 5

Pass variable from jquery to code behind

<asp:Button ID="Button1" runat="server" Text="Submit" />
     <script>
        $(document).ready(function () {
           $("#Button1").click(function () {
                var list = [];
                var a= $("#TextBox1").val();
                var b= $("#TextBox2").val();
                var count = a* b;
                list.push('test');
                for (var i = 1; i <= count; i++) {
                   var item = $("#DropDownList_" + i + "_").find(":selected").text();
                   list.splice(i, 0, item);
                   console.log(list.join());
                   alert(list[i]);
                 }              
             });
       });
     </script>

Hello guys first time at the stack! I have this jquery code that get all choices of dropdown list and store it in array. I want pass this array to c# so I can store the values in DB, please help.

Upvotes: 0

Views: 4362

Answers (1)

Rahul Singh
Rahul Singh

Reputation: 21825

You can simply do this using jQuery ajax:-

var dataToSend = { "Data": list};
$.ajax({
           type: "POST",
           dataType: "json",
           contentType: "application/json; charset=utf-8",
           url: "Default.aspx/SaveData",
           data: JSON.stringify(dataToSend),
           success: function (msg) {
                //success data if any 
           },
           error: function (msg) { //handle error here }
     });

Add this method in your page behind (Default.aspx.cs):-

[WebMethod]
public static void SaveData(string[] Data)
{
     //Save data to DB
}

Upvotes: 1

Related Questions