I'm currently struggling to send an array of long's to an .NET Core MVC Action. I get an error 400.
What I'm trying to achieve is to send the array of longs [1,2,3,...] to the action and then return data but it's just not triggering.
errors: {$: [,…]} $: [,…] 0: "The input does not contain any JSON
tokens. Expected the input to start with a valid JSON token, when
isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine:
0." status: 400 title: "One or more validation errors occurred." traceId: "|9434a014-4b2c198fc0bb7bd6." type:
"https://tools.ietf.org/html/rfc7231#section-6.5.1"
Controller
[HttpGet("SchedulesById")]
public async Task<JsonResult> GetSchedulesById(long[] ids)
{
//Get data from database
return new JsonResult(null);
}
Javscript function
//id is the array.
var array = [1, 2, 3, 4, 5];
var jsonData = { ids: array };
console.log(jsonData);
$.ajax({
type: "GET",
cache: false,
url: "../API/Schedules/SchedulesById/",
data: jsonData,
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
console.log("Schedule: Success [" + id + "]");
console.log(data);
},
failure: function () {
console.log("Schedule [" + id + "]: Failed.");
},
statusCode: {
500: function () {
console.log("Schedule [" + id + "]: Failed.");
}
}
Related
Although the code works as expected it throws
"An error occurred whilst trying to contact the server: 200 parsererror SyntaxError: Unexpected end of JSON input"
The success branch is never called but the data arrives to the api.
Should I be concerned and solve it or it probably won't cause problems elswhere? Thank you for your help.
<script>
$(document).ready(function () {
$("#Save").click(function () {
var data2send = JSON.stringify("test");
$.ajax({
url: 'https://localhost:44348/api/products/PostProduct',
type: 'POST',
data: data2send,
contentType: 'application/json',
dataType: 'json',
success: function (data2send) {
console.log(data2send);
},
error: function (jQXHR, textStatus, errorThrown) {
console.log("An error occurred whilst trying to contact the server: " + jQXHR.status + " " + textStatus + " " + errorThrown);
console.log(data2send);
}
});
});
});
</script>
Controller
[HttpPost]
[Route("PostProduct")]
public void Post([FromBody] string obj)
{
Product.prod.Add(new Product() { ProductId = 12, ProductName = obj, Price = 12 });
}
I have an ajax call that gets data from a REST api.
$.ajax({
url: "http://localhost:52139/odata/WEB_V_CIVIC_ADDRESS",
data: { enteredText: "'" + $('#addressTextField').val() + "'" },
type: "GET",
dataType: 'json',
ContentType: "application/json",
success: function (data) {
alert(JSON.stringify(data));
response($.map(data.accountaddressList, function (item) {
return {
item: item.civicaddress,
value: item.accountNumber,
label: item.civicaddress
}
}));
},
error: function (data, xml, errorThrown) {
alert('Error loading address list: ' + errorThrown);
}
});
The odata returned from that call looks like:
{
"#odata.context":"http://localhost:52139/odata/$metadata#WEB_V_CIVIC_ADDRESS/AValues.Classes.Entities.AccountAddress","value":[
{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88887,"rowNumber":0,"civicaddress":"123 Fake St"
},{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88888,"rowNumber":0,"civicaddress":"321 Faker St"
}
]
}
So the current code throws an 'Undefined' error on the line: response($.map(data.accountaddressList, function (item) {
How do I map the 'civicaddress' and 'accountNumber' from each value in the odata response to 'item'?
Thanks.
I got it, needed to change it to response($.map(data.value, function (item)
There is an Api method called via Ajax. After parsing and other necessary things has been finished, I get the following result.
["IG4","E1 ","E16"]
As soon as the results received, it calls another MVC ActionResult to display data from the database, where the postcode attribute of the object contains one of these Json results. However it does not work.
public ActionResult SearchResult(JsonResult postcode)
{
var posts = db.Posts.Where(p => p.PostCode.Contains(postcode));
return PartialView("postlist", posts);
}
When the ActionResult is called via Ajax, I checked what url is being called and got the following result
SearchResult?postcode%5B%5D=IG4&postcode%5B%5D=E1+&postcode%5B%5D=E16
$('#searchBtn').on('click', function () {
var _postcode = $('#searchPostcode').val();
var _distance = $('#searchDistance').val();
alert("postcode " + _postcode + " distance " + _distance);
var _url = '#Url.Action("GetPostcodesWithin", "Api/PostcodeApi")'; // don't hard code url's
$.ajax({
type: "GET",
url: _url,
data: { postcode: _postcode, distance: _distance },
success: function(data) {
alert("search ok");
$.ajax({
type: "GET",
url: '#Url.Action("SearchResult", "Posts")',
data: { postcode: data },
success: function (data) {
alert("Post results called");
$("#postList").html(data).show();
},
error: function (reponse) {
alert("error : " + reponse);
}
});
},
error: function (reponse) {
alert("error : " + reponse);
}
});
});
Json data returned from GetPostcodesWithin method is displayed on the top, which is passed onto SearchResult
You first need to change the method to
public ActionResult SearchResult(IEnumerable<string> postcode)
Then change the 2nd ajax call to
$.ajax({
type: "GET",
url: '#Url.Action("SearchResult", "Posts")',
data: { postcode: data },
traditional: true, // add this
success: function (data) {
....
}
})
The parameter postcode in the SearchResult() method will then contain the 3 string values from your array.
Because you now have a collection of strings, your query now needs to be
var posts = db.Posts.Where(p => postcode.Contains(p.PostCode));
Side note: Your second value contains a space ("EF ") which may need to be trimmed?
I have this code:
public JsonResult EkranBilgiListele(List<int> ids)
{
dbReklam db = new dbReklam();
//int[] ids = { 14, 16 }; ids comes like this
db.Configuration.ProxyCreationEnabled = false;
var secilenEkranlar = db.tbl_Ekranlar.Where(ekranlar => ids.Contains(ekranlar.sektorID));
return Json(secilenEkranlar);
}
And an AJAX call:
$.ajax({
type: 'POST',
url: '#Url.Action("EkranBilgiListele")',
dataType: 'json',
data: { ids: arraySecilenEkranlarID },
success: function (data) {
console.log('---->' + data.ekranAd);
},
dataType: "json",
traditional: true
});
However, using breakpoints and results view always returns 'empty' and the console returns 'undefined'
Really sorry I wrote wrong query!
Writing right one.
public JsonResult EkranBilgiListele(List<int> ids)
{
//int[] ids = { 14, 16 }; ids comes like this
db.Configuration.ProxyCreationEnabled = false;
var secilenEkranlar = db.tbl_Ekranlar.Where(ekranlar => ids.Contains(ekranlar.ekranID));
return Json(secilenEkranlar);
}
ajax code, changed a little bit:
$.ajax({
type: 'POST',
url: '#Url.Action("EkranBilgiListele")',
dataType: 'json',
data: { ids: arraySecilenEkranlarID },
success: function (secilenEkranlar) {
$.each(secilenEkranlar, function (i, ekranlar) {
console.log(ekranlar.ekranAd);
});
},
error: function (ex) {
alert('İlçeler Çekilemedi.' + ex);
}
});
I got 'bad request" message on the below Rest API Ajax call, When I tested on Developer console it return data successfully.
var _url = auth.get("instance_url") +
"/services/data/v28.0/query/?q=SELECT Id, Name FROM Account WHERE Website LIKE '%gmail.com%' ";
$.ajax({
url: _url,
cache: false,
async: false,
type: 'GET',
contentType: 'application/json',
headers: {
'Authorization': 'OAuth ' + auth.getAccessToken()
},
success: function (data) {
console.log("accounts: " + JSON.stringify(data));
result = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + +errorThrown);
}
});
You need to URLEncode the query parameter, spaces are not valid in a query string, e.g.
var _url = auth.get("instance_url") + "/services/data/v28.0/query?q=" + encodeURIComponent("select id,name from account");