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
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)
Related
I have the following function on WebService with 3 optional params:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string ObtenirPoble(string CP = "", int Codi = 0, string Nom = "")
{
List<clsPoble> llista = _r.getListPobles(CP, Codi, Nom);
JavaScriptSerializer jss = new JavaScriptSerializer();
string resultat_Json = jss.Serialize(llista);
return resultat_Json;
}
The problem is not to make optional params because i already make it on the WebService.
My problem is when i'm sending an ajax call using json with just 1 param like this because it trigger the error before run WebService code
//Object to send
var dataObject = {};
dataObject[config.busqueda] = $(elemId).val();
var json = JSON.stringify(dataObject);
$(elemId).autocomplete({
source: function (request, response) {
$.ajax({
url: config.webService,
data: json,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
//Code...
}
});
}
});
And i get the following error "Invalid call to the Web service. Missing value for the parameter".
I know that i can solve this sending default values of all params but my question is if is possible to send just one param and how i can do this?
In my ASPX page, I have a WebMethod which returns a class object to a JQuery ajax request. This is my code, and it's perfectly wroking. But, I have a doubt if I need to parse it before returning object back from WebMethod (the commented code). What's the best practice ?
[WebMethod]
public static clsEntityContacts Test(string contactID, string entityID)
{
clsEntityContacts result = new clsEntityContacts();
result.contactID = "123";
result.entityID = "12";
//System.Text.StringBuilder sb = new System.Text.StringBuilder();
//JavaScriptSerializer jse = new JavaScriptSerializer();
//jse.Serialize(result, sb);
//return sb.ToString();
return result;
}
This is JQuery ajax request
$.ajax({
url: "Entities.aspx/Test",
data: '{contactID:1, entityID:1}',
type: "POST",
contentType: "application/json",
success: function (data) {
alert(data.d.contactID );
},
error: function (data) {
alert('error!');
}
});
In my c# mvc4 application I have three objects I wish to pass to an ActionResult using an AJAX post with Jquery. The objects are two strings and a form collection. Ive had no problems passing only the form collection, but cant seem to get the syntax correct for passing all three. Here is what Ive tried:
$(document).ready(function () {
$('#ChangeName').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
type: "POST",
data: {tdata + origname + newname},
url: "Home/ChangeName",
success: function (result) { success(result); }
});
});
Ive also tried commas after each variable name in the data: section with and without the brackets. How can I pass all three? When its been successful both string values have populated correctly when debugging but the values dont appear in the ActionResult and show null instead.
Ive also tried placing this below data: contentType: "application/x-www-form-urlencoded",
Here is the beginning of my ActionResult as well:
public ActionResult ChangeName(string Name, string updatedName, FormCollection mCollection)
Can you try:
$(document).ready(function () {
$('#ChangeName').click(function (e) {
var tdata = $('#form1').serialize();
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
type: "POST",
data: {
mCollection: tdata,
Name: origname,
updatedName: newname
},
url: "Home/ChangeName",
success: function (result) { success(result); }
});
});
I think the problem is how you are putting the origname and newname in the ajax request.
Try this:
var origname = $('#NameDiv').find('input[name="myName"]').first().val();
var newname = $('#NameDiv').find('input[name="updatedName"]').first().val();
$.ajax({
url: 'Home/ChangeName',
type: "POST",
data: $("#form1").serialize() + "&origname =" + origname + "&newname =" + newname,
success: function (result) { success(result); }
});
I am calling a WebMethod from jQuery doing the following:
function WebMethod(fn, paramArray, successFn, errorFn) {
var paramList = {};
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
paramList[paramArray[i]] = paramArray[i + 1];
}
}
var params = $.toJSON(paramList);
$.ajax({
type: 'POST',
url: '../../PricingEngine/ContractView.aspx' + '/' + fn,
contentType: 'application/json; charset=utf-8',
data: params,
dataType: 'json',
success: successFn,
error: function(xhr, status, error) {
// Display a generic error for now.
alert("AJAX Error!");
}
});
}
// Used returned object to populate every field
function updateTextFields(result) {
//do some processing here
}
function failed(result) {
alert('failed');
}
// EVENTS
// ------------------------------------------------------------
$(".editableField").keydown(function(e) {
WebMethod('PriceContract',
[
'AQ', aq.val(),
'SOQ', soq.val()
], updateTextFields, failed);
});
The JSON string after the .toJSON has been called:
{"AQ":"140000","SOQ":"1169"}
The C# method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static ContractsListPricing PriceContract(string AQ, string SOQ)
{
ContractsListPricing clp = new ContractsListPricing();
clp.Aq = 1;
clp.Soq = 2;
return clp;
}
This is returning the following error:
Invalid JSON: (Followed by the complete HTML of the current page).
Please take no notice of the logic in the C# as this isn't implemented yet. I am using the jquery-json plugin to parse the JSON.
Thanks
Ive run a demo of your code and got it working fine. Have you checked that you have the ScriptModule Handler set correctly in your web.config?
You're sure the exact url is '../../PricingEngine/ContractView.aspx' + '/' + fn ?
Because ContractView.aspx IS your current webpage
I don't need anything fancy or complex, I'm just trying to pass a simple string across as a parameter to my web method. How can I do it?
Here is the web method call
[WebMethod]
public static ArrayList GetColumns(string TorVName)
here is the JSON call:
<script type="text/javascript" language="javascript">
var qs = new Querystring();
var v1 = qs.get("TorVName");
var jsonData = JSON.stringify(v1);
$().ready(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetColumns",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
var optString = '<option value="-1">Select Column</option>';
$.each(msg.d, function(index, item) {
optString += '<option value="' + item + '">' + item + '</option>';
});
$('select[name^=DDLColumns]').html(optString);
},
error: function() {
alert("Failed to load columns");
}
});
});
</script>
Here is the essence of my web method:
public static ArrayList GetColumns(string TorVName)
{
String cnstr = "myconnectstring";
//string TorVName = System.Web.HttpContext.Current.Request.QueryString["TableOrViewName"];
//string TorVName = "Aged";
//JavaScriptSerializer serializer = new JavaScriptSerializer();
string TorVName = System.Web.HttpContext.Current.Request.QueryString["TOrVName"].ToString();
string Sql = String.Empty;
I think its stupid and disheartening that this needs to be so complex and difficult.
Thanks Dean
In your ajax request, for the data parameter, do it like this:
data: "myData=" + jsonData,
Then in your web method, match the argument to "myData" like this:
[WebMethod()]
public static ArrayList GetColumns(string myData)
{
.....Your code
}
Your web method is smart enough to match the parameter to the argument if the names are the same. Once you receive your string, then you can deserialize it and call your non-webmethod to instantiate your custom data object.
If I understand what you want you just need to append the query string to your url in your ajax call:
url: "Default.aspx/GetColumns?param=value",
I could not understand what you want exactly. Anyway from my point of view, I see you're using JQuery. I have written a JQuery plugin to call ajax methods easier. you can download it from: http://www.4shared.com/file/Y72VBeLc/PageMethod.html
Usage:
$.PageMethod('PageMethodName', successFunction, failFunction, 'param1', param1, 'param2', param2, ...);
An example:
Javascript:
var myName = 'TestName';
var myId = '123';
$.PageMethod('ReturnCustomData', onSuccess, onFail, 'MyName', myName,'MyID', myId);
Code Behind:
public class CustomData
{
public string name;
public int id;
}
[WebMethod()]
public static CustomData ReturnCustomData(string MyName, int MyID)
{
CustomData MyData = new CustomData();
MyData.name = MyName;
MyData.id = MyID;
return MyData;
}
The success function can have a serialized json object as a return value. in your callback function, you can access the CustomData
function onSuccess(response)
{
alert('Your Name: ' + response.d.name + ', Your ID: ' + response.d.id);
}
function onFail(response)
{
alert("An error occurred.");
}