简体   繁体   中英

Receive multiple AJAX JSON Data with C# Params

I'm trying to create a function that handles multiple parameters being received from an AJAX call using C# params . But the server throws an internal server error 500 . Here is what the scenario looks like:

The mean function may pass as many arguments it wants say at least two to as many as 20(without considering performance at this point of time).

First, here is my working code that passes the parameters as comma-separated string, which is received by the server and is processed successfully

function mean(textboxA, textboxB, textboxC) {
        var textboxC = textboxC.id;
        event.preventDefault();

        $.ajax({
            type: "POST",
            url: "Default.aspx/calculateMean",
            data: '{ strTextBoxes:"' + textboxA.value + ',' + textboxB.value + '"}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                event.preventDefault();
                document.getElementById(textboxC).value = data.d;
            }
        });
    }

At the server-side, the C# code resides in Default.aspx , which is as follows:

<script runat="server">

    [System.Web.Services.WebMethod]
    public static string calculateMean(string strTextBoxes)
    {

        List<string> listTextBoxes = new List<string>();
        foreach (string temp in strTextBoxes.Split(','))
        {
            listTextBoxes.Add(temp);
        }

        string strA = listTextBoxes.ElementAt(0).ToString();
        string strB = listTextBoxes.ElementAt(1).ToString();
        if (String.IsNullOrEmpty(strA))
        {
            strA = "0";
        }

        if (String.IsNullOrEmpty(strB))
        {
            strB = "0";
        }
        float floatA = Convert.ToInt32(strA);
        float floatB = Convert.ToInt32(strB);

        string mean = Convert.ToString(ClassLibrary1.Common.mean(floatA,floatB));
        return mean;
    }
</script>

After customizing the code to use C# params technique, the jQuery looks like follows:

<script type="text/javascript">
    function mean(textboxA, textboxB, textboxC) {
        var textboxC = textboxC.id;
        event.preventDefault();
        var JSONData = JSON.stringify({ strValues1: textboxA.value, strValues2: textboxB.value });
        console.log(JSONData);
        $.ajax({
            type: "POST",
            url: "Default.aspx/calculateMean",
            data: JSONData,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                event.preventDefault();
                document.getElementById(textboxC).value = data.d;
            }
        });
    }
</script>

and server-side Default.aspx looks like:

<script runat="server">

    [System.Web.Services.WebMethod]
    public static string calculateMean(params string[] values)
    {


        string strA = values[0];
        string strB = values[1];
        if (String.IsNullOrEmpty(strA))
        {
            strA = "0";
        }

        if (String.IsNullOrEmpty(strB))
        {
            strB = "0";
        }
        float floatA = Convert.ToInt32(strA);
        float floatB = Convert.ToInt32(strB);

        string mean = Convert.ToString(ClassLibrary1.Common.mean(floatA,floatB));
        return mean;
    }
</script>

When the above modified code is run, it shows internal server error 500 Ajax内部服务器错误

You are passing an JSON object:

{ "strValues1": "6", "strValues2": "5" }

and you are expecting a string array.

You must pass an array of strings as your back-end method is defined. Try it like this:

var arrayArguments = [];
arrayArguments.push(textboxA.value);
arrayArguments.push(textboxB.value);
var JSONData = JSON.stringify(arrayArguments);
console.log(JSONData);

If you want various values with their names kept you should go with the first option and send a JSON object (convert it to a string before sending it) then deserialize it in the WebMethod :

var strJsonObj = JSON.stringify({x:'12',y:'45',z:'786'});

C#

[System.Web.Services.WebMethod]
public static string calculateMean(string strJsonObj)

Or you can go with a string array if you don't care for the variables names :

var strJsonArr = JSON.stringify(['12', '45', '786', '444']);

C#

[System.Web.Services.WebMethod]
public static string calculateMean(params string[] strJsonArr)

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