accessing the parameters of a JSON call in the web method - c#

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.");
}

Related

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
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)

Trying to pass an array object to my web service controller but it always null

I just want to pass an array object from my javascript to controller. though up to alert it gives checkbox value,So i believe there is nothing wrong in javascript. In controller the object is null always. what did i do wrong here?
function amal() {
var selected = [];
$('input[type="checkbox"]:checked').each(function () {
selected.push($(this).val());
});
alert(selected);
$.ajax({
url: "http://localhost:63138/api/Emptbles/LoadAmal",
type: "POST",
data: selected,
contentType: "application/json",
success: function (response) {
alert("success");
myFunction();
},
error: function () {
}
});
My api controller
[HttpPost]
public IHttpActionResult LoadAmal(List<selectedSymptoms>list)
{
string item1 = "";
string item2 = "";
string item3 = "";
for (int i = 0; i < list.Count; i += 3)
{
//grab 3 items at a time and do db insert,
// continue until all items are gone..
item1 = list.ElementAt(i+0).ToString(); ;
item2 = list.ElementAt(i + 1).ToString(); ;
item3 = list.ElementAt(i + 2).ToString(); ;
// use the items
}
string query = "EXEC Add_Employee'" + item1 + "','" + item2 + "','" + item3 + "'";
int result = connectionProvider.CreateSomething(query);
return Ok(result);
}
My selectedSymptoms class(i dont know whether this is right,just want to take jason object to the controller. thank you)
public class selectedSymptoms
{
public void PassThings(List<selectedSymptoms> symtoms)
{
var t = symtoms;
}
}
The scenario you're running into is a serialization issue between the object you're sending and the Web API. Microsoft gives you code to test this process, which I would recommend you use because it will teach you a lot.
What you're sending in your response would probably look like this :
["someValue1", "someValue2", "etc"]
The Type in your API needs to be serializable, and there's no possible way of doing that given your current class. If all you want to do is send a list of strings, then you should not use a complex object at all and simply use List<string>. If you do indeed want to use a complex object, it needs properties to map the data to.
If I had a class
public class Person
{
public string Name {get; set;}
}
And I wanted to post a javascript object representation of that, my code would look like :
var people = [];
$('input[type="checkbox"]:checked').each(function () {
var Person = new Object();
Person.Name = $(this).val();
people.push(Person);
});
$.ajax({
url: "http://localhost:63138/api/Emptbles/LoadAmal",
type: "POST",
data: people,
contentType: "application/json",
success: function (response) {
},
error: function () {
}
});
You can see how we are basically creating an array of a JavaScript-version of our C# class, and it can easily map the Name property between the 2 objects.
API would look like :
public IHttpActionResult GetStuff(List<Person> peeps) {}
Try this:
data: { 'list' : selected }

AJAX Return object contains d in asp.net web form

Hey guys Its a simple question but want to stop ajax return object contains d.
I asp.net web form
$.ajax({
type: "POST",
url: myurl,
data: JSON.stringify({value:"1"}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
//alert("i am in success");
console.log(result);
},
failure: function (response) {
console.log("I am in failure");
}
});
and
in .cs file
[WebMethod]
public static string getSpareParts(string value)
{
List<data> spareParts;
using (var db = new WaltonCrmEntities())
{
spareParts = db.SpareParts.Select(x => new data
{
id = x.ItemID,
text = x.ItemName
}).ToList();
}
JavaScriptSerializer js = new JavaScriptSerializer();
return js.Serialize(spareParts);
//return spareParts;
}
when result is return it will contain result in result.d but i want to stop this d thing .Simply result should be the result. Can anybody solve this.
There's not much you could do about this. That's the way ASP.NET WebMethods always serialize the response. The reason why Microsoft decided to wrap the response in this .d property is to protect against this particular JSON hijacking vulnerability. Of course you could always check in your success callback whether this property is present or not:
success: function (result) {
var data = result.hasOwnProperty('d') ? result.d : result;
console.log(data);
}
Also I would very strongly recommend against writing plumbing code in your WebMethod (like serialization stuff) and just return the proper object and let the infrastructure care about serialization:
[WebMethod]
public static List<data> getSpareParts(string value)
{
using (var db = new WaltonCrmEntities())
{
return db.SpareParts.Select(x => new data
{
id = x.ItemID,
text = x.ItemName
}).ToList();
}
}
Now inside your success callback you can directly work with this collection without the need to additionally JSON.parse it:
success: function (result) {
var data = result.hasOwnProperty('d') ? result.d : result;
for (var i = 0; i < data.length; i++) {
console.log('id: ' + data[i].id + ', text: ' + data[i].text);
}
}

Serialize json before returning from asp.net WebMethod

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!');
}
});

Error calling web method from jQuery

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

Categories

Resources