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