How to httppost a list of objects? - javascript

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

Related

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

Ajax Not Working With C# Controller Action With 2D Array Parameter

My Ajax is not hitting my controller action. What could be the reason?
My Controller Action
public ActionResult Save_Data(string [][] rosterArray, int Pricelist_Id, int Group_Id)
My Ajax
$.ajax({
url: '#Url.Action("Save_Data", "PriceListMaster")',
type: 'Post',
async: false,
contentType: 'application/json',
dataType: "json",
data: { "rosterArray": rosterArray, "Pricelist_Id": "2", "Group_Id": $("#Group_Id").val() },
//data: JSON.stringify({ "Item_Code": Item_Code, "IPD_Price": IPD_Price, "OPD_Price": OPD_Price, "EMS_Price": EMS_Price }),
success: function (data) {
debugger
if (data.success)
{
alert('Data Saved Successfully.');
location.reload();
} else {
alert(data.error_msg);
}
}
}
If you are using type: 'Post' in AJAX, that means you need to add a Request type in Controller.
Try using this in controller,
[HttpPost]
public ActionResult Save_Data(string [][] rosterArray, int Pricelist_Id, int Group_Id)
Use httpPost in the Method for define type of response.
at client side
$.ajax({
url: '#Url.Action("Save_Data", "PriceListMaster")',
type: 'Post',
async: false,
contentType: 'application/json',
dataType: "json",
data: { "rosterArray": JSON.stringify(rosterArray), "Pricelist_Id": "2", "Group_Id": $("#Group_Id").val() },
//data: JSON.stringify({ "Item_Code": Item_Code, "IPD_Price": IPD_Price, "OPD_Price": OPD_Price, "EMS_Price": EMS_Price }),
success: function (data) {
debugger
if (data.success)
{
alert('Data Saved Successfully.');
location.reload();
} else {
alert(data.error_msg);
}
}
}
and your controller code can be like this:
[HttpPost]
public ActionResult Save_Data(string rosterArray, int Pricelist_Id, int Group_Id)
{
string [][] convertedArray = JsonConvert.DeserializeObject<string [][]>(rosterArray);
}
Hope this works
Note: But you need to incude using Newtonsoft.Json;

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.

Differentiate between HTTP request and Ajax request

I am currently working on ASP.NET WebApi and Angularjs
WebApi have a method
[System.Web.Http.AcceptVerbs("POST")]
[System.Web.Http.HttpPost]
public HttpResponseMessage SearchAddress(SearchDetails searchDetail)
{
//13.03993,80.231867
try
{
if (!WebSecurity.IsAuthenticated)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotAcceptable);
return response;
}
List<CollegeAddress> CollegeAddress = addressService.GetAddressFromDistance(17.380498, 78.4864948, 2000);
HttpResponseMessage responseData = Request.CreateResponse(HttpStatusCode.Accepted, CollegeAddress);
return responseData;
}
catch (Exception e)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.NotFound);
return response;
}
}
And I have to call this method from client side.
When I call this method using Ajax, it's not working, the method parameter searchDetail is always null if I use Ajax.
$.ajax({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
type: "json",
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).success(function (response) {
return response;
}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})
But when I call that method via HTTP request, it is working.
$http({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
data: searchDetail,
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).success(function (response) {
toastr.success('Account Created successfully!', 'Account Created');
return response;
}).error(function () {
toastr.error('Somthing is wrong', 'Error');
})
Why? What is the difference between them? Why is Ajax not working and HTTP is?
jQuery's ajax() sends the data with Content-type: x-www-form-urlencoded.
Angular's $http sends the data with Content-type: application/json
Your server obviously expects JSON, but you set up the $.ajax() call incorrectly for that.
According to the docs:
The method property doesn't seem to exist.
The type property is supposed to determine the type of the request (e.g. 'GET', 'POST', etc.).
In order to change the default content-type to application/json you can use the contentType property.
I have not tried it myself, but something like this should work:
$.ajax({
type: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
contentType: 'application/json; charset=utf-8'
});
$.ajax({
method: 'POST',
url: rootUrl + '/api/Address/SearchAddress',
async: false,
data: searchDetail,
I assume that searchDetail is an object. This is what the docs say about the data property:
... It is converted to a query string, if not already a string.
So if the server expects JSON then you have to convert it to JSON first:
data: JSON.stringify(searchDetail),
And as #ExpertSystem has pointed out you have to change method to type.
First you are duplicating the HttpPost, so just keep the second (and remove the namespace)
Second you want search detail to come from the body so decorate it with [FromBody]
[HttpPost]
public HttpResponseMessage SearchAddress([FromBody]SearchDetails searchDetail)
{

$.ajax - send object for data property

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.

Categories