简体   繁体   中英

Pass array from client side to service side c#

I am calling a javascript function on button click using onclientclick with below function.

 function addValues() {
        debugger;
        var arrValue = [];
        var hdnValue = document.getElementById("hdn").value;
        var strValue = hdnValue.split(',');
        for (var i = 0; i < strValue.length; i++) {
            var ddlValue = document.getElementById(strValue[i]).value;
            arrValue.push(ddlValue);
        }
    }

arrValue array will have all the required values and how can I move this array values to server side for further process.

Update 1:

HTML:

function addValues() {
        debugger;
        var arrddlValue = [];
        var hdnddlValue = document.getElementById("hdnDDL").value;
        var strddlValue = hdnddlValue.split(',');
        for (var i = 0; i < strddlValue.length; i++) {
            var ddlValue = document.getElementById(strddlValue[i]).value;
            arrddlValue.push(ddlValue);              
        }
    }

    $.ajax({
        url: '',
        data: { ddlArray: arrddlValue },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: false,
        success: function (data) {

        },
        error: function (x, e) {
        }
    });

Code:

protected void btnSort_Click(object sender, EventArgs e)
    {
        try
        {
            if (Request["ddlArray[]"] != null)
            {
                string[] arrValues = Array.ConvertAll(Request["ddlArray[]"].ToString().Split(','), s => (s));
            }
        }
     }

If your framework is ASP.Net you can pass it by $.ajax , I am passing array like:

$.ajax({
url: '',
data: {  AbArray: arrValue },
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data) {

},
error: function (x, e) { 
}

});

and get it in Back-end like:

if (request["AbArray[]"] != null)
{
    int[] arrValues = Array.ConvertAll(request["AbArray[]"].ToString().Split(','), s => int.Parse(s));
}

suppose array is int .

the above sample is using Generic-Handler .

if you want to use webmethod do something like:

[WebMethod(EnableSession = true)]
public static void PassArray(List<int> arr)
{ 
}

and Ajax would be like:

function addValues() {
debugger;
var arrddlValue = [];
var hdnddlValue = document.getElementById("hdnDDL").value;
var strddlValue = hdnddlValue.split(',');
for (var i = 0; i < strddlValue.length; i++) {
    var ddlValue = document.getElementById(strddlValue[i]).value;
    arrddlValue.push(ddlValue);
} 
var jsonVal = JSON.stringify({ arr: arrValue });
$.ajax({
    url: 'YourPage.aspx/PassArray',
    data: jsonVal,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    async: true,
    success: function (data) {

    },
    error: function (x, e) {
    }
});
}

Change Ajax Url as your PassArray address which mean YourPage.aspx should be change to page name which have PassArray in it's code-behind.

For more info Read This .

If you are using Asp.net WebForm Application,

Approach 1 : you can store your array value in a hidden input control and retrieve the saved data in your c# coding.

Approach 2 : define web method in your server side c# code and pass this javascript array value as ajax call.

link for Approach 1 : https://www.aspsnippets.com/Articles/Pass-JavaScript-variable-value-to-Server-Side-Code-Behind-in-ASPNet-using-C-and-VBNet.aspx

link for Approach 2 : https://www.aspsnippets.com/Articles/Send-and-receive-JavaScript-Array-to-Web-Service-Web-Method-using-ASP.Net-AJAX.aspx

I would "stringify" the array by imploding it with a special char unlikely to appear in my values (for example: §), and then with the help of jQuery.ajax() function, I will send it to the backend (ASP.NET MVC) action method:

$.ajax({
   url : 'http://a-domain.com/MyController/MyAction',
   type : 'POST'
   data : 'data=' + myStringifiedArray;
});

My backend would be something like this (in MyController class):

[HttpPost]
public ActionResult MyAction(string data)
{
    string[] arrValue = data.Split('§');
    ...
}

UPDATE

For ASP.NET forms, the ajax request would be:

$.ajax({
   url : 'http://a-domain.com/MyPage.aspx/MyMethod',
   type : 'POST'
   data : 'data=' + myStringifiedArray;
});

And the backend would be something like this:

[System.Web.Services.WebMethod]
public static void MyMethod(string data)
{
    string[] arrValue = data.Split('§');
    ...
}

You will find a more precise explanation here: https://www.aspsnippets.com/Articles/Call-ASPNet-Page-Method-using-jQuery-AJAX-Example.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM