Model binding is binding my json array, but not the values - c#

I am using ASP.NET MVC 3 and I'm trying to model bind a simple json array to a List<JsonPositions>. JsonPositions is a custom object with the same properties as the json objects in the array.
Here is what my array looks like on the client:
var widgetPositions = [
{ col: 5, row: 1, id: 2 },
{ col: 4, row: 5: id: 40 }
];
$.ajax({
url: 'the url',
data: { positions: widgetPositions },
success: function () {
alert('Save successful.');
},
error: function () {
alert('An error occurred while trying to update the widget positions.');
}
});
This code appears to be working correctly when the request is examined in Chrome.
In the controller we have the following action method:
public void UpdatePositions(List<JsonPosition> positions)
{
// debugging here
}
When I examine the widgetPositions list it does have two items just like the json array, but the objects' properties do not match the values from the objects on the client. Here is what the object JsonPosition looks like:
public class JsonPosition
{
public int id { get; set; }
public int col { get; set; }
public int row { get; set; }
}
Thanks for any help you can offer :)

I think you may need to add the content-type:
$.ajax({
url: 'the url',
data: JSON.stringify({ positions: widgetPositions }),
contentType: 'application/json',
success: function () {
alert('Save successful.');
},
error: function () {
alert('An error occurred while trying to update the widget positions.');
}
});
Also you're not specifying a request type, so it will do a GET by default, do you mean to be doing a POST? That would make it
$.ajax({
url: 'the url',
type: 'POST',
data: JSON.stringify({ positions: widgetPositions }),
contentType: 'application/json',
success: function () {
alert('Save successful.');
},
error: function () {
alert('An error occurred while trying to update the widget positions.');
}
});

You could send them as a JSON object:
var widgetPositions = [
{ col: 5, row: 1, id: 2 },
{ col: 4, row: 5: id: 40 }
];
$.ajax({
url: 'the url',
data: JSON.stringify({ positions: widgetPositions }),
contentType: 'application/json',
success: function () {
alert('Save successful.');
},
error: function () {
alert('An error occurred while trying to update the widget positions.');
}
});
Things to notice that you hadn't in your code and which will make it work:
contentType: 'application/json', - set the proper request content type header
data: JSON.stringify({ positions: widgetPositions }) - send a JSON request
Now you will happily get all you need here:
public void UpdatePositions(List<JsonPosition> positions)
{
// debugging here
}
Remark: The JSON.stringify method is natively defined in all modern browsers (even in IE8, even if this is far from being a modern browser). But if you need to support some prehistoric browsers you could include the json2.js script to your page which will check whether the browser natively supports this method and if not provide an implementation.

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 error when there's a parameter in url

I have a ajax code that fills a dropdownlist and I use mvc c#.
When I call to my method from ajax and I have an url in the directions bar without parameters the code works correctly, but if I have a parameter in url in the directions bar this not working and appears this error:
"{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}".
Here's my code:
$.ajax({
url:"../Records/myList",
type: "POST",
dataType: 'json',
contentType: 'application/json',
// data: JSON.stringify(Data),
success: function (resul) {
Function(resul);
},
error: function (message) {
}
});
My url: http://localhost:123/Record/EditRecord ->> so it's works
My other url: http://localhost:123/Record/EditRecord/1 ->> It does not work like this
Thanks in advance.
From given second URL (which doesn't work) I assume that you want to use jQuery AJAX with HttpGet method. The URL pattern matches this route:
http://localhost:123/{controller}/{action}/{id}
which id treated as UrlParameter.
Hence you need to use action argument & data representing URL parameter values, like this example:
Controller
[HttpGet]
public ActionResult EditRecord(int id)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "GET",
dataType: 'json', // response type
contentType: 'application/x-www-form-urlencoded; charset=utf-8', // header content type
data: { id: 1 },
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Alternatively a direct usage of URL parameter is applicable for GET methods without specifying data content:
View (JS)
$.ajax({
url: "Record/EditRecord/1",
type: "GET",
processData: true, // this is important to use in GET methods
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
NB: Use jQuery.get for simplified version:
$.get("/Record/EditRecord/1", function (result) {
Function(result);
}, "json").error(function (message) { // throw error
});
PS: This is an example for HTTP POST request if you're looking for proper POST method with AJAX.
Controller
[HttpPost]
public ActionResult EditRecord(Record rec)
{
// other stuff
}
View (JS)
$.ajax({
url: "/Record/EditRecord",
type: "POST",
dataType: 'json', // response type
contentType: 'application/json; charset=utf-8', // header content type
data: JSON.stringify({ rec: { id: 1, name: 'XXXX', ... }}),
success: function (result) {
Function(result);
},
error: function (message) {
// throw error
}
});
Reference:
Do GET, POST, PUT, DELETE in ASP.NET MVC with jQuery AJAX
i cant see any fault in the code but i suggest to try let the param come with it's name at server either if you choose to use data propery (of ajax function):
{key1: 'value1', key2: 'value2'}
or you use string query:
page?name=ferret&color=purple
bacuse you've just say that first method was work i assume there is no need to check POST/GET method.
EDIT:
be award to this.

Get null parameter in the server side after ajax call

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

Send complex data to C# with jQuery

I have a JavaScript object like so that I want to send to C# (question right at the bottom)
var data = {
mykey1: "somevalue",
mykey2: "somevalue2",
addProducts: [
{
id: 1,
quantity: 3,
variation: 54
},
{
id: 2,
quantity: 5,
variation: 23
}
]
}
It is to add either a single product or multiple products to a users basket. I want to send an array of objects back..
I can access this in Javascript by using
data.addProducts[1].id
using the below...
$.ajax({
url: "/ajax/myurl",
data: data,
dataType: "json",
type: "GET",
success: function( response ){
// Data returned as JSON
}
});
it is sending the data like this (URLdecoded for your reading pleasure)
?mykey1=somevalue&mykey2=somevalue2&addProducts[0][id]=1&addProducts[0][quantity]=3&addProducts[0][variation]=54&addProducts[0][id]=2&addProducts[0][quantity]=5&addProducts[0][variation]=23
My question is... without using JSON.stringify on the data, which will just send it as a full object in the url /ajax/myurl/{mykey1:1 ...}
How can I read this information back in from C#? jQuery is just encoding it as the standard way, should I be doing anything else to this, and is there a built in way to grab this data in C#?
var strValue = $(getStringValue);
var intValue = $(getIntValue)
$.ajax({
type: \"post\",
url: \"default.aspx/getData\",
data: \"{\'postedAjaxStringValue\"\': \'\" + encodeURIComponent(strValue) + \"\', postedAjaxIntValue: \" + encodeURIComponent(intValue ) + \"}\",
contentType: \"application/json; charset=utf-8\",
dataType: \"json\",
success: OnSuccess,
failure: function (response) {
error: function (response) {
});
//ON C# KodeBehind..
[System.Web.Services.WebMethod]
public static string getData(string postedAjaxStringValue, int postedAjaxIntValue){}

Categories

Resources