Passed Json is not accepted by controller - javascript

I get this result from creating JSON in my view
header:{"ScheduledVisit":"08/02/2017 12:00 AM","Company":"fdsa","ContactPerson":"asfd","Phone":"asdf","Purpose":"fasd","Detail":"asdf"}
My model looks like this:
public class ScheduleVisit
{
[Required(ErrorMessage = "* Required")]
public DateTime ScheduledVisit { get; set; }
public string Company { get; set; }
public string ContactPerson { get; set; }
public string Phone { get; set; }
public string Purpose { get; set; }
public string Detail { get; set; }
}
I pass my data like so:
document.getElementById("btn_submit_schedule").addEventListener("click", function (event) {
event.preventDefault();
if ($("#scheduledVisit").val().length === 0) {
$("#scheduledVisit").focus();
}
var obj = {};
obj.ScheduledVisit = document.getElementById("scheduledVisit").value;
obj.Company = document.getElementById("company").value;
obj.ContactPerson = document.getElementById("contactPerson").value;
obj.Phone = document.getElementById("phone").value;
obj.Purpose = document.getElementById("purpose").value;
obj.Detail = document.getElementById("detail").value;
console.log(obj);
addSchedule(obj);
});
function addSchedule(data) {
$.ajax({
type: "POST",
url: "#Url.Action("ScheduleVisit", "ScheduleVisit")",
data: {header: JSON.stringify(data)},
success: function(result) {
alert(result);
},
error: function(error) {
alert(error);
}
});
}
and my controller looks like this:
[HttpPost]
public JsonResult ScheduleVisit(ScheduleVisit header)
{
return Json(false);
}
When I run in debug mode and check if my controller accepts anything, I get null on the "header" parameter. Please show me where I am getting it wrong.

Just replaced data: {header: JSON.stringify(data)} with data: data with current solution.
This very complex and manual way you'll can use simple way as following
Assign name field to every element as same like id now
<input type="text" name="Company" value="" />
Use serializeArray
data: $("form").serializeArray(),
Hope this will help.

The problem is that "data: {header: JSON.stringify(data)}" is not the same object as you expect on the controller.
This should work.
$.ajax({
type: "POST",
url: "#Url.Action("ScheduleVisit", "ScheduleVisit")",
data: data,
...
The controller expects an object like:
{
"ScheduledVisit":"08/02/2017 12:00 AM",
"Company":"fdsa",
"ContactPerson":"asfd",
"Phone":"asdf",
"Purpose":"fasd",
"Detail":"asdf"
}

Related

Ajax Post (Model binded) passing null to the controller

I am making an AJAX POST request to the controller (ASP.NET Core MVC), yet the value for the parameter is coming through as null. I tried several solutions given on StackOverflow. But, I couldn't correct it. Please help.
My view collects class fees information. There may have more than one payment.
$(function () {
$('#sendSlip').click(function (e) {
e.preventDefault();
let fees = new Array(); //To store payment info
let tb = $('#feesTable:eq(0) tbody');
//Collecting info of each payment
tb.find("tr").each(function () {
let row = $(this);
let fee = {};
if (row.find('input:checkbox:first').is(':checked')) {
fee.ClassId = row.find("TD").eq(0).html();
fee.FeeId = row.find("TD").eq(1).html();
fee.Amount = row.find(".fee").html();
fee.Month = row.find(".month").html();
fees.push(fee);
}
});
//Arranging data to send to controller
var data = {
fees: fees,
Bank: $(".bank").val(),
PaidAmount : $(".amount").val(),
PaidDate : $(".date").val()
};
console.log(data);
$.ajax({
type: 'POST',
url: '#Url.Action("StudentPayment_Create", "StudentPayment")',
contentType: "application/json",
headers: { 'RequestVerificationToken': gettoken() },
data: //{ data: JSON.stringify(data) },
JSON.stringify(data) ,
})
});
});
Model
public class StudentPaymentSlipVM
{
public StudentPaymentPaidClassVM fees { get; set; }
public string Bank { get; set; }
public DateTime PaidDate { get; set; }
public int PaidAmount { get; set; }
}
Controller
public ActionResult StudentPayment_Create([FromBody] List<StudentPaymentSlipVM> data)
{
---
}
Object details at runtime
From your attached screenshot for data to be passed to the controller, the data's structure was unmatched with the data model the controller expected.
Assume the data structure for the front-end is correct.
Controller should expect that the received data is a StudentPaymentSlipVM object. While in the StudentPaymentSlipVM object, the fees is a StudentPaymentPaidClassVM array.
Model
public class StudentPaymentSlipVM
{
public List<StudentPaymentPaidClassVM> fees { get; set; }
public string Bank { get; set; }
public DateTime PaidDate { get; set; }
public int PaidAmount { get; set; }
}
Controller
public ActionResult StudentPayment_Create([FromBody] StudentPaymentSlipVM data)
{
}
While from your JQuery part, make sure that your data object to be passed to API must be matched with the data type as your model in the back-end.
var data = {
fees: fees,
Bank: $(".bank").val(),
PaidAmount : parseInt($(".amount").val()),
PaidDate : $(".date").val()
};
I tried to pass my data to controller by binding to a ViewModel (StudentPaymentSlipVM) which has all required definitions. But I couldn't do it. So I changed the way and pass my object to Controller as following way now it is working.
And also I would like to thanks Yong Shun.
Changed the JQuery code
$.ajax({
type: 'POST',
url: '#Url.Action("action", "controller")',
headers: { 'RequestVerificationToken': gettoken() },
data: dataObj,
})
I changed the Controller
[HttpPost]
public ActionResult StudentPayment_Create(List<StudentPaymentPaidClassVM> Fees, string Bank, decimal PaidAmount, DateTime PaidDate)
{
.....
}

Posting JSON with a array object to MVC controller

My ViewModel is:
public class CFUViewModel
{
public int RID { get; set; }
public int Order { get; set; }
public List<VCItem> VItems{ get; set; }
}
where VCItem is:
public class VCItem
{
public string Name{ get; set; }
public string Category { get; set; }
}
In my view, I am collecting the data from form elements. Thus,
$('#submit').click(function () {
console.log(gatherData());
transmitData(gatherData());
});
function gatherData() {
var vc = dataObject.getVCItems();
//This is a knockout function that gives an array of VCItems
var data = new Object();
data.RID = $('#rid').val();
data.VItems = vc;
return data;
};
function transmitData(dataToSend) {
$.ajax({
url: '../CFUDashboard/ReceiveData',
type: 'post',
dataType : 'json',
success: function (data) {
alert('success');
},
data: dataToSend
});
};
In the controller, I have:
[HttpPost]
public ActionResult ReceiveData(CFUViewModel viewModel)
{
//...
}
The problem is, though RID is ok, VItems list is not serialized. I suspect, the reason is, the array attached to the JS object is actually string (array wrapped in quotes). This is confirmed by the console.log(gatherData())
It is outputted as:
VItems : "[{"Name":"OPV3","Category":"FUGY"},{"Name":"OPV7","Category":"FUGX"}]"
What is the reason for not getting the list serialized? What am I missing?

How can I validate my model when I have an array property?

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

Controller recieving empty data from Ajax

I'm trying to send a collection from a view to a controller, using ajax. First I complete the data in a javascript array, and then I try to pass it to the server:
var funciones = $("#funcionesUsuario").data("kendoGrid").dataSource.data();
var func = [];
for (var i = 0; i < funciones.length; i++) {
func.push({
"Estado": 1,
"FechaAlta": null,
"UsuarioAlta": null,
"FechaModificacion": null,
"UsuarioModificacion": null,
"BitConcilia": funciones[i].BitConcilia,
"BitLectura": funciones[i].BitLectura,
"BitSupervisa": funciones[i].BitSupervisa,
"ConciliacionId": funciones[i].ConciliacionId,
"UsuarioId": funciones[i].UsuarioId
})
}
$.post(url, { funcionesUsuario: func })
.done(function (data) {
alert("good job");
});
Then, since I'm sending data for 2 objects, my parameter is a IEnumerable of said object:
public void ActualizarFuncionesUsuario(IEnumerable<FuncionUsuario> funcionesUsuario)
{
//do something
}
My problem is that the controller receives 2 objects, as I can see in the funcionesUsuario.count, but they are both empty.
I tried sending int, bool and other types of variables with success, so I suspect I'm doing something wrong regarding data binding.
Below I attached pictures of what I'm sending and what I'm receiving in the other side.
This is the FuncionUsuario model: `
public class FuncionUsuario : AuditableEntity {
public int ConciliacionId { get; set; }
public int UsuarioId { get; set; }
public bool BitLectura { get; set; }
public bool BitConcilia { get; set; }
public bool BitSupervisa { get; set; }
public virtual Conciliacion Conciliacion { get; set; }
[Display(ResourceType = typeof(Global), Name = "Descripcion")]
[NotMapped]
public string Descripcion { get; set; }
}
first construct you array as java script objects
var funciones = $("#funcionesUsuario").data("kendoGrid").dataSource.data();
var func = [];
for (var i = 0; i < funciones.length; i++) {
func.push({
Estado: 1,
FechaAlta: null,
UsuarioAlta: null,
FechaModificacion: null,
UsuarioModificacion: null,
BitConcilia: funciones[i].BitConcilia,
BitLectura: funciones[i].BitLectura,
BitSupervisa: funciones[i].BitSupervisa,
ConciliacionId: funciones[i].ConciliacionId,
UsuarioId: funciones[i].UsuarioId
})
}
Next, properly stringify them
var payload = JSON.stringify(func);
Then post it as JSON
$.ajax({
url: url,
type: "POST",
contentType: "application/json",
dataType: 'json'
data: payload,
});
Try these:
Specify json as the dataType
$.post(url, { funcionesUsuario: func })
.done(function (data) {
alert("good job");
}, 'json');
Use $.ajax instead: docs
$.ajax({
url: url,
data: JSON.stringify(func),
contentType: "application/json",
type: "POST"
});

Format JSon so that mvc4 controller method can parse it

My controller Action:
[HttpPost]
public ActionResult H80Count(IEnumerable<H80SearchCriteria> model)
{
do some stuff and return Json;
}
My model:
public class H80SearchCriteria
{
public int ID { get; set; }
public int Operator { get; set; }
public string FieldID { get; set; }
public string Kriterie { get; set; }
}
My Javascript:
var SearchCriteria = [];
var i = 0;
$('#tableSearchValues > tbody').find('tr').each(function () {
i += 1;
var row = {
ID : i,
Operator : $(this).data('operator'),
FieldID : $(this).data('fieldid'),
Kriterie: $(this).data('kriterie')
};
SearchCriteria.push(row);
});
var url = '/MyController/H80Count';
var data = JSON.stringify(SearchCriteria) ;
$.ajax({
type: 'POST',
url: url,
data: data,
etc...
The Json that is passed looks like this:
[{"ID":1,"Operator":1,"FieldID":1,"Kriterie":11211},{"ID":2,"Operator":1,"FieldID":1,"Kriterie":11211}]
I can't see why it is not parsed correctly. What am I missing?
I think you forgot the contentType: 'application/json' on ajax function.
It works for me.
try this instead of IEnumerable use array and place [FromUri] or [FromBody] which looks for values in the Uri or Body of the request.
[HttpPost]
public ActionResult H80Count([FromUri] H80SearchCriteria[] model)
{
do some stuff and return Json;
}
and dont forget to set the traditional ajax settings as true
$.ajax({
type: 'POST',
url: url,
data: data,
traditional: true
});

Categories

Resources