The value of List<Order> returns as null in my controller action method while sending the complex object. Can someone help to identify the issue? Do we need to pass array of objects with indexes?
JavaScript
function OnCustomerClick() {
//var orders = [];
//orders.push({ 'OrderId': '1', 'OrderBy': 'Saroj' });
var complexObject = {
FirstName: 'Saroj',
LastName: 'K',
//Orders : orders
Orders: [{ OrderId: 1, OrderBy: 'Saroj' }, { OrderId: 2, OrderBy: 'Kumar' }]
};
var obj = { customer: complexObject };
var data2send = JSON.stringify(obj);
$.ajax({
type: "POST",
url: 'Home/TestCustomer1',
data: data2send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (arg) { //call successfull
},
error: function (xhr) {
//error occurred
}
});
};
MVC
public ActionResult TestCustomer1(Customer customer)
{
return Json(customer);
}
C#
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
List<order> Orders { get; set; }
}
public class order
{
public int OrderId { get; set; }
public string OrderBy { get; set; }
}
You need to use public properties for model binding. Orders currently has no access modifier, so its private.
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<order> Orders { get; set; } // <----
}
Other than that, everything looks fine.
Related
I have a class with an array property in MVC
public class MyClass
{
public int Contrato_Id { get; set; }
public string Contrato { get; set; }
public int Torre_Id { get; set; }
public string Torre { get; set; }
public SkillsATB[] Skills { get; set; }
}
When I do the POST via jquery ajax my ModelState validation is always false
if (ModelState.IsValid)
{
var _current = _Service.Insert(current);
return Json(new { result = "success", resultValue = "" });
}
debuggin image here here
The property SkillsATB is ok, it has elements, but I think I am missing something for that array.
function ConvertToSkillsObject(id, name) {
var skill = {
Id: Math.round(id),
Nombre: name,
Descripcion: "",
Activo: "1",
Asignada: 1
}
return skill;
}
function GetSkillsAsignados() {
var asignados = [];
$("#sortable2").children().each(function () {
var item = ConvertToSkillsObject($(this).attr("data-id"), $(this).html())
asignados.push(item);
});
return asignados;
}
var MyClass= {
Correo: $('#correo').val(),
CorreoLider: $('#correoLider').val(),
CorreoLiderBSD: $('#correoLiderBSD').val(),
FechaNacio: $('#fechaNacio').val(),
Contrato_Id: $('#contrato_Id').val(),
Torre_Id: $('#torre_Id').val(),
Skills: GetSkillsAsignados()
};
$.ajax({
url: "../../MyController/Save",
type: "POST",
data: JSON.stringify(MyClass),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (e) {
... //more javascript
Remove the property from the model before validating: ModelState.Remove("Skills");
SOLVED
The problem was in a datepicker CSS, something was wrong in the format date. Nothing to do with the prior before
I am currently trying to send an object with a list, but I do not understand why sends the object but the list I receive zero.
Structure:
public class Provider
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Articles> Articles { get; set; }
}
public class Articles
{
public int Id { get; set; }
public string Name { get; set; }
}
Javascript
var articles = [];
articles.push({ Id: 1, Name: "Article Name 1" });
articles.push({ Id: 2, Name: "Article Name 2" });
var provider = {
Id: 1,
Name : "Provider Name",
Articles : articles
};
And i used this call ajax
$.ajax({
contentType: 'application/json; charset=utf-8',
url: "/Provider/Save",
type: 'post',
dataType: 'json',
data: JSON.stringify({ provider: provider}),
cache: false,
success: function (data) {
alert("success");
},
error: function () {
alert("error");
}
});
Controller
[HttpPost]
public ActionResult Save(Provider provider)
{
// Code here
return View();
}
I wrote this Controller:
[HttpPost]
public JsonResult CheckOut(List<POS_model> pos, double totalPayment)
{
try
{
var json = JsonConvert.SerializeObject(pos);
DataTable posTable = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
posTable.Columns["discount_percent"].ColumnName = #"Discount %";
POS m_pos = new POS();
m_pos.Data = posTable;
m_pos.totalPayment = totalPayment;
m_pos.CheckOut();
return Json(new
{
Status = "Success"
});
}
catch
{
return Json(new
{
Status = "Fail"
});
}
}
And i attempted wrote this AJAX script to call and submit the parameters to the Controller:(but it didn't work)
var totalPay = 1000;
var GatherPosItems = $('#tblPOS').tableToJSON();
$.ajax({
type: 'POST',
data: JSON.stringify(GatherPosItems)+"&totalPayment="+totalPay,
url: '#Url.Action("CheckOut", "POS")',
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert('Success');
},
error: function (req, status, errorObj) {
alert(errorObj.toString());
}
});
The GatherPosItems is a JSON with multiple "Rows" or Objects, so it's an array.
I added a parameter totalPayment.
How can i pass Both GatherPosItems and totalPayment to the Controller?
my Model:
public class POS_model
{
public string Qty { get; set; }
public string description { get; set; }
public string price { get; set; }
public string discount_percent { get; set; }
public string Discount_amount { get; set; }
public string Discounted_price { get; set; }
public string Line_total { get; set; }
public string is_vat { get; set; }
public string track_type { get; set; }
public string item_line_id { get; set; }
public string id { get; set; }
public string sale_code { get; set; }
public string reference { get; set; }
public string unit_of_measure { get; set; }
public string location { get; set; }
public string item_code { get; set; }
}
My GatherPosItems's RESULT:
You concatenate a non-JSON string (&totalPayment="+totalPay) to the JSON returned from JSON.stringify function, which corrupts the format of data being sent to the server and makes the model binder unable to parse it.
The following should work:
$.ajax({
type: 'POST',
data: JSON.stringify({pos: GatherPosItems, totalPayment: totalPay}),
url: '#Url.Action("CheckOut", "POS")',
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert('Success');
},
error: function(req, status, errorObj) {
alert(errorObj.toString());
}
});
I know I've done this before but I can't seem to get this to work.
I have the following JavaScript;
$("#btnTestVouchers").click(function () {
var postData = {
"workplaceGiverId": $(".wpgDropdownList").val(),
"fromMemberId": $(".wpgFromMemberDropdownList").val(),
"toMemberId": $(".wpgToMemberDropdownList").val(),
"voucherExpiryDate": $("#expiryDatePicker").val(),
"recipients": JSON.stringify("[{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}]")
};
console.log(postData);
$.ajax({
type: "POST",
url: "/Admin/TestVoucherCreationEmails",
contentType: 'application/json; charset=utf-8',
dataType: "json",
data: JSON.stringify(postData),
success: function (d) {
alert("OK");
},
error: function (xhr, textStatus, errorThrown) {
alert("Error:" + errorThrown);
}
});
});
In my model I have;
public class postDataObject
{
public int workplaceGiverId { get; set; }
public int fromMemberId { get; set; }
public int toMemberId { get; set; }
public string voucherExpiryDate { get; set; }
public IEnumerable<BulkVoucherRecipient> recipients { get; set; }
}
public class BulkVoucherRecipient
{
public string firstname { get; set; }
public string lastname { get; set; }
public string email { get; set; }
public string voucheramount { get; set; }
}
In my controller I have;
[HttpPost]
public void TestVoucherCreationEmails(postDataObject postedData)
{
string g = "";
}
However when I post, the list of recipients is always empty.
If I don't Stringify the list of recipients I get the same result.
Anyone know what I'm doing wrong?
edit
The other values all come through ok, just the List is empty.
You don't need to JSON.stringify the recipients.
"recipients": JSON.stringify("[{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}]")
Remove JSON.stringify form here and it should work.
var postData = {
"workplaceGiverId": $(".wpgDropdownList").val(),
"fromMemberId": $(".wpgFromMemberDropdownList").val(),
"toMemberId": $(".wpgToMemberDropdownList").val(),
"voucherExpiryDate": $("#expiryDatePicker").val(),
"recipients": [{'firstname':'a','lastname':'b','email':'c','voucheramount':'d'}]
};
Try this, It should work
[HttpPost]
public void TestVoucherCreationEmails([FromBody]postDataObject postedData)
{
string g = "";
}
Background:
In the view, we ask (via jquery and ajax) the controller for data from the database. The data is returned as Json, but for reasons unknown one part of the Json object is returned as null, even though it is properly set in the controller's JsonResult.
The Code:
The class to be returned as JsonResult
public class InData
{
public InData() { }
public AppsWithActions[] apps { get; set; }
public User[] users { get; set; }
public string timePeriod { get; set; }
public string startDate { get; set; }
public string endDate { get; set; }
public string dataType { get; set; }
}
The Problem is the string arrays actionIds and actionNames in the following class are null in the javascript, even though they have the correct values in the JsonResult:
public class AppsWithActions
{
public AppsWithActions() { }
public string id { get; set; }
public string name { get; set; }
public string[] actionIds { get; set; }
public string[] actionNames { get; set; }
}
The controller function that sets the InData and returns it to the javascript:
//Takes a goal setting, turns it to indata and returns a JsonResult
public JsonResult GetIndataFromGoalSettingId(SettingId settingId)
{
var id = ToGuid(settingId.idString);
GoalSetting setting = Session.Query<GoalSetting>()
.Where(x => x.Id == id)
.FirstOrDefault();
var indata = TransformGoalSettingToInData(setting);
return Json(new { returnvalue = indata }, JsonRequestBehavior.AllowGet);
}
The ajax call that returns everything correct, except the apps.actionIds and apps.actionNames
function getIndataFromGoalSettingId(settingId) {
if (settingId != null) {
settingIdIn = { "idString": settingId};
$.ajax({
type: "POST",
async: false,
traditional: true,
url: 'GetIndataFromGoalSettingId',
data: JSON.stringify(settingIdIn),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
//...
}
});
}
}
It should be said that we have successfully used the same kind of infrastructure for getting data and returning it as Json to the javascript before, but if anyone has a better suggestion feel free to spell it out!