$.ajax - send object for data property - javascript

I'm trying to call an asmx web service method with jQuery and pass an actual JavaScript object for the data, and get JSON back. The closest I can come is this:
$.ajax({
url: "WebService.asmx/HelloWorld",
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ num: 12, name: "Adam" }),
dataType: "json",
success: function (data) { alert(data.d); }
});
How can I successfully make this call without first stringifying my object?
I tried this (removing the contentType)
$.ajax({
url: "WebService.asmx/HelloWorld",
type: "POST",
data: { num: 12, name: "Adam" },
dataType: "json",
success: function (data) { alert(data.d); }
});
But that returns the result in XML, not json.
Here's the web method:
[WebMethod]
[ScriptMethod]
public string HelloWorld(int num, string name) {
return ++num + name;
}
EDIT
Here's a screenshot of the headers of the request. Clearly content-type is set to xml for the response.

Set the ResponseFormat:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld(int num, string name) {
return ++num + name;
}
Just a NOTE: asmx doesn't return JSON for GETs only POST
Per Dave's Comments
It is impossible with the ASMX and ASPX JSON endpoints. They require the application/json Content-Type and a POST request or no JSON.

Related

Passing list of integers from AJAX call to C# method returns null

I am trying to pass an array of integers from my client-side javascript to server-side C# using ajax. However it always comes up as null in code-behind. I can't seem to find the issue here. I had a similar ajax method but with an array of strings and it works, but it doesn't with integers?
My ajax method:
var theList = [1,2,3,4,5];
$.ajax({
type: 'POST',
url: 'MyPage?handler=SaveList',
dataType: 'json',
contentType:'application/json; charset=utf-8',
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify({ theList: theList }),
success: function(data){
alert("Success");
}
});
My code-behind:
public JsonResult OnPostSaveList([FromBody]int[] theList) //<<<Returns 'null'
{
foreach(int data in theList){
//save to datebase
}
return new JsonResult("Done");
}
The issue here is I get a null value from theList in the code-behind.
Checking the JSON.stringify, it seems to be passing "[1,2,3,4,5]". Not sure if there is a type mis-match here.
The Max value of int32 is 2147483647, while 1609430400000 is out of range, so you receive the null value.
Instead of int[], you can use long[] to receive the value.
var theList = [1609430400000, 1609516800000, 1609603200000];
$.ajax({
type: 'POST',
url: 'Index?handler=SaveList',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(theList),
success: function (data) {
alert("Success");
}
});
Handler:
public JsonResult OnPostSaveList([FromBody] long[] theList) //<<<Returns 'null'
{
foreach (var data in theList)
{
//save to datebase
}
return new JsonResult("Done");
}
Request Payload:
Result:

How to httppost a list of objects?

I have this list of objects which I need to send from my angularjs javascript code:
var dataToSend = [{
SubId: "c9cb1d3e-8c32-4a9e-8f0d-0008196776de",
CustomerName: "Blah"
}, {
SubId: "aaaa1d3e-8c32-4a9e-8f0d-0008196776de",
CustomerName: "Blah2"
}]
I've tried these different variations but none of them are working:
1.
$http.post("url",
{
dataType: 'json',
headers: {
contentType: "application/json; charset=utf-8",
},
method: "POST",
data: dataToSend,
}).then...
2.
$http.post("url",
{
data: $.param(dataToSend),
}).then...
3
$http.post("url",
{
data: angular.toJson(dataToSend),
}).then...
4
$http.post("url",
{
data: { customers: dataToSend },
}).then...
5
$http.post("url",
{
data: JSON.stringify({ customers: dataToSend }),
}).then...
My API side code is (I have tried with [FromBody] attribute but no luck there):
[HttpPost]
public async Task<JsonResult> CreateCustomers(List<Customer> customers)
{
// customers is always null
}
And this is my Customer.cs:
public partial class Customer
{
public System.Guid SubId { get; set; }
public string CustomerName { get; set; }
}
Can you please help me? I have tried posting to CreateCustomers(Customer c) without using a list and its working as expected. But when I use a list, its always coming as null on the other side.
EDIT:
$.ajax is working but $http.post isn't. Any idea why?
var request = $.ajax({
dataType: "json",
url: "url",
method: "POST",
data: { '': dataToSend }});
Are you sending JSON ( Include dataType: 'json')
$http({
url: "url",
dataType: 'json',
method: 'POST',
data: dataToSend,
headers: {
contentType: "application/json; charset=utf-8",
}
})
In C# add FromBody in parameter
[HttpPost]
public async Task<JsonResult> CreateCustomers([FromBody]]List<Customer> customers)
{
// customers is always null
}
More on Ajax parameters
contentType is the type of data you're sending, so application/json; charset=utf-8 is a common one, as is application/x-www-form-urlencoded; charset=UTF-8, which is the default.
dataType is what you're expecting back from the server: json, html, text, etc.
This should work. post full code if you face issue
use [ModelBinder] in front of your param.
[HttpPost]
public async Task<JsonResult> CreateCustomers([ModelBinder]List<Customer> customers)
{
// customers is always null
}
Web API only uses model binding for simple types, falling back on formatters for everything else. Adding [ModelBinder] forces the complex types to use model binding anyway.
Your post data is not matched with the parameter List<Customer>.
Change your server side method to something like:
[HttpPost]
public async Task<JsonResult> CreateCustomers(JObject queryParam)
{
// populate your list here
// for eaxample : var customers = queryParam["customers"].ToString();
}
And also you can use this code to send data to the server:
$http({
url: 'url',
dataType: 'json',
method: 'POST',
data: jsonData,
headers: { "Content-Type": "application/json" }
}).success(function(response){ $scope.response = response;
}).error(function(error){ $scope.error = error; });

Submitting Ajax request from external javascript file in ASP.NET MVC

I am trying to submit an ajax request from an external JavaScript file in ASP.NET MVC. I'm getting a 500. What am I doing wrong?
Ajax call (From external JS file)
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Controller Action Method (That should be catching the request)
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
[HttpGet]
public void AjaxEndpoint()
{
var thing = 1 + 2;
}
// AJAX endpoint for GetProducts.js
[HttpPost]
public void AjaxEndpoint(string jsonData)
{
var thing = 1 + 2;
}
}
Error I'm getting
You either need to remove the contentType option
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: { jsonData: "testing" },
dataType: "json",
success: successFunc,
error: errorFunc
});
or alternatively, stringify the data
$.ajax({
type: "POST",
url: '/Home/AjaxEndpoint',
data: JSON.stringify({ jsonData: "testing" }),// modify
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
Your ajax call needs to be to an ActionResult in the controller, The controller performs and returns the data to the page
[HttpPost]
public ActionResult ajaxcall(string ids)
{
String Data = code to perform
return Json(Data);
}
this is the basic idea. Javascript makes the call and uses the json data returned on the clients page

Javascript object received as null in mvc controller

Below is my AJAX GET request that is trying to pass few parameters including a javascript object to a mvc controller but the object is always received as null:
var sort = { column: 'UserName', order: 'desc' };
var sortParameter = JSON.stringify(sort);
$.ajax({
url: '#Url.Action("GetUsers", "Account")',
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: { skipRecords: vm.pageIndex * 1000, sortParam: sortParameter },
success: function (data) {
}
});
The controller method looks like below:
[HttpGet]
public JsonResult GetUsers(int skipRecords, Sort sortParam, string userName = null)
{
}
Also below is the Sort class defined:
public class Sort
{
public string column { get; set; }
public string order { get; set; }
}
If I dont use JSON.stringify and pass just the javascript object, below is the request that gets sent:
GET /Account/GetUsers?skipRecords=0&sortParam%5Bcolumn%5D=UserName&sortParam%5Border%5D=desc&_=1408990051727 HTTP/1.1
You're probably looking for:
var sortParameter = { column: 'UserName', order: 'desc' };
$.ajax({
url: '#Url.Action("GetUsers", "Account")',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({
skipRecords: vm.pageIndex * 1000,
sortParam: sortParameter }),
success: function (data) {
}
});
The reason your code doesn't work is because if you don't JSON.stringify the entire result, it is passed as a querystring encoded. You can't pass JSON as a value in a querystring encoded value.
Querystring encoded (Post or Get) looks like: a=1&b=2&c=3
So your querystring would look like skipRecords=5&sortParam={column:'UserName',order:'desc' }
MVC Won't double decode querystring and json.
Use POST and prepend [FromBody] to your 'Sort' object parameter in your action method.

How to call ASP.net web method with Array parameter from jQuery Javascript?

I have the following ASP.net web method:
[WebMethod]
public static string SaveUserNew(string id, string[] roles)
{
doStuff(id, roles);
}
I'm calling this code from jQuery Javascript code, but I don't know the syntax for passing an array. Ordinarily, I write jQuery code to call web methods that looks like this:
$.ajax({
type: "POST",
url: "someUrl.aspx?webmethod",
data: '{"foo":"fooValue"}',
contentType: "application/json;",
dataType: "json",
}
Please shed some light on this.
Update: Here is an example of code without arrays that does work:
[WebMethod]
public static string SaveUserNew(string id)
{
return "0";
}
var jdata = '{ "id": "3TWR3"}';
$.ajax({
type: "POST",
url: "UserMgmt.aspx/SaveUserNew",
data: jdata,
contentType: "application/json;",
dataType: "json",
traditional: true
}
});
My intention is to write some code in a similar style where I pass arrays to my web method.
Passing param to webmethod is a little bit tricky. Try this one
[WebMethod]
public static string GetPrompt(string[] name)
{
return "Hello " + name[0] + " and " + name[1];
}
jscript
var param = "{'name':['jack', 'jill']}";
var option = {
error: function(request, status, error) {
alert(error);
},
cache: false,
success: function(data, status) {
alert(data.d);
},
type: "POST",
contentType: "application/json; charset=utf-8",
data: param,
dataType: "json",
url: "../Server/ArrayParam.aspx/GetPrompt"
};
$.ajax(option);
You need to
1) assign the data parameter to have an object with the properties id and roles.
2) assign the roles property an array of strings.
3) Set the traditional setting to true while passing options to ajax call.
e.g:
$.ajax({
type: "POST",
url: "someUrl.aspx?webmethod",
data: {
"id":"1",
"roles":[
"Admin",
"Something",
"Another Thing"
]
},
contentType: "application/json;",
dataType: "json",
traditional: true //#############################
}

Categories