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);
}
});
}
Related
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.
I have a view with multiple inputs for my Model (Html.TextBoxFor(x => x.attribute) etc. And my ajax method is:
function callMethod() {
$.ajax({
type: "POST",
data: $('#Form').serialize() ,
url: '#Url.Action("formMethod", "Test")',
}).done(function (newTable) {
$('#RefundTableDiv').html(newTable);
});
};
and this works perfectly, the model comes perfectly to formMethod, but when i change formMethod and add another parameter for example 'int test' it doesnt work anymore.
My method looks like:
function callMethod() {
var number = 2;
$.ajax({
type: "POST",
data: {"model": $('#Form').serialize(),
"test": number},
url: '#Url.Action("formMethod", "Test")',
}).done(function (newTable) {
$('#RefundTableDiv').html(newTable);
});
};
the "test": number does come correctly to the method in the controller but the model suddenly is null now?
What am i doing wrong?
Using .serialize() serializes your model as a query string (e.g. someProperty=someValue&anotherProperty=anotherValue&...). To add additional name/value pairs, you can append then manually, for example
var data = $('#Form').serialize() + '&test=' + number;
$.ajax({
....
data: data;
or use the param() method (useful if you have multiple items and/or arrays to add)
var data = $("#Form").serialize() + '&' + $.param({ test: number }, true);
$.ajax({
....
data: data;
you can do it like this:
function callMethod() {
var number = 2;
var sd = $('#Form').serializeArray();
sd.push({ name:"test", value:number });
$.ajax({
type: "POST",
data: sd,
url: '#Url.Action("formMethod", "Test")',
}).done(function (newTable) {
$('#RefundTableDiv').html(newTable);
});
};
Here is my ajax call
$.ajax({
async: false,
url: "/api/clients/UpdateResourceContactProductsByResourceContactId/" + id,
type: 'POST',
data: { strIds: strIds },
success: function (data) {
}
});
where id is the integer and strIds is a string contantenation of integers, they look like 123_254_741_6650 ...
And this the server side code ...
[HttpPost]
public IHttpActionResult UpdateResourceContactProductsByResourceContactId
(int id, string strIds)
{
//...
}
When I hit the update button, I'm getting the following error:
{"Message":"No HTTP resource was found that matches the request URI
'http://localhost/api/clients/UpdateResourceContactProductsByResourceContactId/22757'.",
"MessageDetail":"No action was found on the controller 'Clients' that matches the request."}
Am I missing something?
Try this...
$.ajax({
async: false,
url: "/api/clients/UpdateResourceContactProductsByResourceContactId",
type: 'POST',
data: { id: id, strIds: strIds },
success: function (data) {
}
});
I think you're passing the data wrong. You are passing a object. Either change you method to accept a JObject and use dynamic to pull the strIds out, pass the string by itself, or use it as a URL parameter.
//example using JObject below
[HttpPost]
public IHttpActionResult UpdateResourceContactProductsByResourceContactId(int id, JObject data)//JObject requires Json.NET
{
dynamic json = data;
string ids = json.strIds
}
If you are going to POST an object you need to call JSON.stringify on it too in the javascript.
var data = JSON.stringify({ strIds: strIds });
$.ajax({
async: false,
url: "/api/clients/UpdateResourceContactProductsByResourceContactId/" + id,
type: 'POST',
data: data,
success: function (data) {
}
});
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());
});
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.