Get null parameter in the server side after ajax call - c#

I have a weird problem in my ASP.Net WebApi application. I have this client side code:
var arr = [];
for (var i = 0; i < checkarray.length; i++) {
if (checkarray[i] == 1) arr.push(ids[i]);
}
console.log(arr);
$.ajax({
type: "post",
async: false,
url: "/api/Demande/ReservationAgendaByDrivers",
data: arr,
success: function (data) {
// ...
}
});
In the server side:
[HttpPost]
public IEnumerable<ReservationModel> ReservationAgendaByDrivers(int[] tab)
{
List<ReservationModel> outlst = new List<ReservationModel>();
List<ReservationModel> model = GetListReservation().ToList();
foreach (ReservationModel item in model)
{
if (!item.id_chauffeur.HasValue)
continue;
if (tab.Contains(item.id_chauffeur.Value))
outlst.Add(item);
}
return outlst.OrderByDescending(x => x.id_demande);
}
I get for example, as output in the browser, this array :
[7, 5, 1]
but the tab parameter in the server side is always null !!
I need to know :
What are the reasons of this error?
How can I fix my code?

For the ModelBinder to work correctly you need to provide the array in an object under the tab property. You should also remove the async: false as it is unspeakably bad practice to use it.
$.ajax({
type: "post",
url: "/api/Demande/ReservationAgendaByDrivers",
data: {
tab: arr
},
success: function (data) {
// handle the response here...
}
});

What are the reasons of this error?
int[] tab is expecting a var in the params named tab which is not there as you are trying to send an array arr.
How can I fix my code?
Send an object in the data :
data: { tab: arr }, // here tab is the key which belongs to int[] tab at backend
and async:false is not a good choice to set it to false. This shouldn't be used to set it to false as there are ways to do the things correctly with promises.

console.log(arr);
$.ajax({
type: "post",
url: "/api/Demande/ReservationAgendaByDrivers",
data:{tab:arr},
success: function (data) {
.............
}});

Thanks everybody,
I fix my code by editing my code like this :
$.ajax({
type: "post",
async:false,
url: "/api/Demande/ReservationAgendaByDrivers",
data: JSON.stringify(arr),
contentType: 'application/json; charset=utf-8',
success: function (data) {
.......
}
});

Related

C# and Ajax - Posting 2 values from JS to C#

I'm using ajax to send an int64 and a string from a month selector to my server-side, but my variable is always null or 0.
JS:
function deleteConta(id) {
var data = $("#monthSelector").val();
var params = {
id: id,
dataAtual: data
};
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(params),
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}
C#:
public PartialViewResult OnPostDelete([FromBody] long id, string dataAtual)
{
contaDTO.Remove(id, contaDTO.Database, contaDTO.ContaCollection);
dataCorrente = DateTime.ParseExact(dataAtual, "yyyy-MM", null).AddMonths(1);
contas = BuscarContasUsuarioMes(User.Identity.Name, dataCorrente);
return Partial("_PartialContas", contas);
}
I already checked with debugger and my variables are ok and filled with value expected (One test was like {id: 50, dataAtual: '2023-01'}
Checked a lot of forums, but Couldn't figure out how to make this thing work.
By declaring the number parameter with [FromBody] you tell ASP.NET Core to use the input formatter to bind the provided JSON (or XML) to a model. So your test should work, if you provide a simple model class.
Have you tried to remove it and sending value to the action?
β€”- UPDATE β€”β€”
Try this
function deleteConta(id) {
var data = $("#monthSelector").val();
$.ajax({
type: "POST",
url: '/Contas/ContaView?handler=Delete',
data: { id: id, dataAtual: data },
headers:
{
"RequestVerificationToken": $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (partialReturn) {
$("#partial").html(partialReturn);
}
});
}

Passing dynamic objects from client-side to C#

Passing dynamic objects from client-side to C#
hello friends,
i'm searching for passing a dynamic data, whatever data sent which is value type or reference type or both,
lets see a example as simple
client-side
1st request
var model = {
Id: 10,
Name: 'John'
Active: true
};
$.ajax({
type: 'POST'
url: '#Url.Action("MethodName_ToDo")',
data: JSON.stringify(model)
});
2nd request
var model = {
Email: 'm#m.net'
CurrentSalary: 1500,
CurrencyType: 1
};
$.ajax({
type: 'POST'
url: '#Url.Action("MethodName_ToDo")',
data: JSON.stringify(model)
});
3rd request
var id = '1e575923-d6cf-447e-9163-f7885655e4f5';
$.ajax({
type: 'POST'
url: '#Url.Action("MethodName_ToDo")',
data: {Id : id}
});
server-side
public JsonResult GetData(dynamic model)
{
// my code here...
}
Question:
I need a way to receive a dynamic data.
Is it possible to send dynamic data from client-side(using jquery ajax) to Server-side C# ?!
Please let me know if you have any idea about this question.
Note: I will not vote down, for any answer
i use this for call server-side
var data = {
Name: 'Sam',
Age: "26"
};
$.ajax({
url: "http://localhost:8081/Home/PostData",
type: "POST",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(data),
success: function (data) {
alert(data);
},
error: (xhr, tt, tm) => errorHandler(xhr, tt, tm)
});
function errorHandler(xhr, tt, tm) {
console.dir(xhr, tt, tm);
};
Thank you so much, UW.

Ajax POST not posting list

I am passing data to controller through Ajax call.
Following is the ajax code:
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List[i] = $(selectedItem).text();
});
var from_Month = $("#fromKPAMonthPicker").val();
var from_Year = $("#fromKPAYearPicker").val();
var to_Month = $("#toKPAMonthPicker").val();
var to_Year = $("#toKPAYearPicker").val();
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
success: function (data) {
$("#divList").html(data);
}
});
Controller action method:
[HttpPost]
public ActionResult _DataByFromTo(List<Int32> doj_Month_List, Int16 from_Month, Int16 from_Year, Int16 to_Month, Int16 to_Year)
{
return View();
}
It was working in my old code perfectly fine. I don't know whats the problem. because all data are passing perfectly except this array of jquery.
To disable deep serialization of objects you need to set traditional property to true.
$.ajax({
url: '/Home/_DataByFromTo',
type: "POST",
data: {
doj_Month_List: month_List,
from_Month: from_Month,
from_Year: from_Year,
to_Month: to_Month,
to_Year: to_Year
},
dataType: "html",
traditional: true,
success: function (data) {
$("#divList").html(data);
}
});
When set to true it results in a shallow serialization.
Following link might be of help.
https://api.jquery.com/jQuery.param/
try using push
var month_List = [];
$('#dojMonths :selected').each(function (i, selectedItem) {
month_List.push($(selectedItem).text());
});

C# MVC 4: Passing JavaScript array in View to Controller

In MVC 4, how do you pass a JavaScript array in the View to a function in the Controller with AJAX?
This doesn't seem the work:
$.ajax(
{
type: "POST",
url: "../Home/SaveTable",
data: { function_param: countryArray }
});
Problem is, countryArray is a global array in the JavaScript View and I've check that it has elements in it before being passed. However, when the saveTable function receives the array, the function says it received a null string[] array.
I only know that passing arrays from the Controller to the View, you serialize complex data types with return Json(data, JsonRequestBehavior.AllowGet); and then de-serialize it by setting it to a "var" variable.
So I probably have to do it for this as well, but how to?
Edit 1:
Here is the shortened version of the SaveTable function:
public string SaveTable(string[] function_param)
{
if (function_param != null && function_param > 0)
{
//some code
return "Success";
}
//The following code will run if it's not successful.
return "There must be at least one country in the Region.";
//Yeah it's always returning this b/c function_param is null;
}
You need to set traditional: true when serializing arrays.
$.ajax({
type: "POST",
traditional: true,
url: "../Home/SaveTable",
data: { function_param: countryArray }
});
Found this good explanation on what traditional: true does: https://stackoverflow.com/a/5497151/2419531
EDIT:
If you don't want to use traditional: true, you can pass the data as string using JSON.stringify and specifying the contentType:
$.ajax({
type: "POST",
url: "../Home/SaveTable",
contentType: 'application/json',
data: JSON.stringify({function_param: countryArray}),
});
You should use on your controller:
public string SaveTable(object[] function_param)
{
//some code
}
Should do the work, it's for future users.
your Ajax :
$.ajax({
type: "POST",
url: "../Home/SaveTable",
contentType: 'application/json',
data: {function_param: JSON.stringify(countryArray)},
});
in your controller:
using Newtonsoft.Json;
public string SaveTable(string function_param)
{
dynamic func_param = JsonConvert.DeserializeObject(function_param)
}
then you will be able to do a foreach in your controller.

asp.net json web service sending array error Cannot convert object of type 'System.String' to type 'System.Collections.Generic.List`1[System.String]'

I want to insert data from JavaScript to database using ajax and webservice,
I have some controls which by jQuery I get their values and make an array of their values.
When I send the array it causes this error:
Cannot convert object of type 'System.String' to type'System.Collections.Generic.List1[System.String]'
var variables = Array();
var i=0;
$('#Div_AdSubmition').find('.selectBox').each(function () {
variables[i] = $(this).find('.selected').find(".text").html();
i++;
});
$.ajax({
type: 'post',
data: "{ 'a':'" +variables + "'}",
dataType: 'json',
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
}
});
This is the C# Code
[WebMethod]
public object insertAd(List<string> a)
{
return a;
}
You need to make your data parameter of the $.ajax call like this: JSON.stringify({'a': variables})
The JSON variable is not available in < IE8 so you'll want to include a JSON implementation like the one mentioned in the answer here
Also, you had an extra } in the success function.
So, in the future, if you want to add extra parameters to your data object passed to the web service, you'd construct it like so:
var someArr = ['el1', 'el2'];
JSON.stringify({
'param1': 1,
'param2': 'two'
'param3': someArr
// etc
});
JavaScript:
var variables = Array();
var i = 0;
$('#Div_AdSubmition').find('.selectBox').each(function () {
variables[i] = $(this).find('.selected').find(".text").html();
i++;
});
$.ajax({
type: 'post',
data: JSON.stringify({'a': variables}),
dataType: 'json',
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
});
});
C#
[WebMethod]
public object insertAd(List<string> a)
{
return a;
}
data: Data to be sent to the server. It is converted to a query string, if not already a string. It’s appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.
So, try to add a new parameter to your ajax call:
$.ajax({
type: 'post',
data: { 'a': variables }, // Notice some changes here
dataType: 'json',
traditional: true, // Your new parameter
url: 'HomeWebService.asmx/insertAd',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("data : " + data.d);
}
});
Try this way. Maybe you'll need to change the Web service method to expect an array instead of a List, but I'm not sure.
Try this
data: JSON.stringify({ 'a': variables }),

Categories

Resources