I was trying several ways to pass the list of objects to the controller but
the controller always receives null
Here is my code:
View:
$('#btnSave').click(function () {
var arrPropIdPos = new Array();
$('.property').each(function () {
var obj = {
PropertyId : $(this).attr('PropertyId'),
Xposition : $(this).attr('xPos'),
Yposition : $(this).attr('yPos')
};
arrPropIdPos.push(obj);
});
var jsonData = JSON.stringify(arrPropIdPos);
$.ajax({
url: "/PropertyPosition/Insert/",
type: 'POST',
data: jsonData,
dataType: 'json',
//...
},
console.log(arrPropIdPos);
0: Object
PropertyId: "1"
Xposition: "11"
Yposition: "55"
__proto__: Object
1: Object
PropertyId: "2"
Xposition: "651"
Yposition: "48"
__proto__: Object
console.log(jsonData);
[{"PropertyId":"1","Xposition":"11","Yposition":"55"},
{"PropertyId":"2","Xposition":"651","Yposition":"48"}]
Controller (option 1):
[HttpPost]
public JsonResult Insert(string jsonData)
{
// jsonData is null
}
Controller (option 2):
public class PropertyPositionInsert
{
public string PropertyId { get; set; }
public string Xposition { get; set; }
public string Yposition { get; set; }
}
public JsonResult Insert(List<PropertyPositionInsert> model)
{
// model is null
}
Try to wrap your array into an object with a property model:
var jsonData = JSON.stringify({model: arrPropIdPos});
Also try to set dataType option to 'application/json'.
$('#btnSave').click(function () {
var arrPropIdPos = new Array();
$('.property').each(function () {
var obj = {
'PropertyId' : $(this).attr('PropertyId')
,'Xposition' : $(this).attr('xPos')
,'Yposition' : $(this).attr('yPos')
};
arrPropIdPos.push(obj);
});
$.ajax({
type: 'POST',
contentType: "application/json",
data: JSON.stringify(arrPropIdPos),
url: "/PropertyPosition/Insert/"
});
Class:
public class PropertyPositionInsert
{
public string PropertyId { get; set; }
public string Xposition { get; set; }
public string Yposition { get; set; }
}
Controller:
public JsonResult Insert(PropertyPositionInsert[] model)
{
}
I have run into this in the past and have found that if you set
traditional: true
in your jQuery ajax call, it shjould fix the issue.
$('#btnSave').click(function () {
var arrPropIdPos = new Array();
$('.property').each(function () {
var obj = {
PropertyId : $(this).attr('PropertyId'),
Xposition : $(this).attr('xPos'),
Yposition : $(this).attr('yPos')
};
arrPropIdPos.push(obj);
});
var jsonData = JSON.stringify(arrPropIdPos);
$.ajax({
beforeSend: function () {
},
type: "POST",
"async": true,
url: "/PropertyPosition/Insert/",
data: JSON.stringify(obj),
dataType: "json",
contentType: "application/json",
success: function (data) {
},
error: function (xhr, textStatus, error) {
},
complete: function () {
},
})
Controller:
Create a class or model
public class PropertyPositionInsert
{
public string PropertyId { get; set; }
public string Xposition { get; set; }
public string Yposition { get; set; }
}
public IHttpActionResult JsonResult (PropertyPositionInsert obj)
{
obj.PropertyId;
obj.Xposition ;
obj.Yposition;
}
you can check the values in above obj
Related
I need to pass map (dictionary) to the MVC controller along with a string parameter.
var reportName= 'ReportName';
var FilterValues = new Map([
[0, "value1"],
[1, "value2"],
[2, "value3"],
]);
var model = { reportName: reportName, FilterValues: JSON.parse(FilterValues) };
$.ajax({
url: '/Reports/ExportReport/',
type: 'POST',
contentType: "application/json",
data: model,
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
public void ExportReport(string reportName, Dictionary<int, string> FilterValues)
{
Also tried this with Object instead of map . It returns me a success but doesn't hit the controller.
let FilterValues = {
1: "value1",
2: "value2",
3: "value3",
};
var report = 'test';
// var data = ('#DesignationReport').DataTable().$('input,select,textarea').serialize();
var model = { reportName: report, FilterValues: FilterValues };
This is the last thing I tried.
Since JSON does not support ES2015 constructs such as Map. We need to have custom class as bellow:
public class ViewModel
{
public List<FilterValue> FilterValues { get; set; }
public string ReportName { get; set; }
}
public class FilterValue
{
public int Id { get; set; }
public string Value { get; set; }
}
Your post method will be:
[HttpPost]
public ActionResult ExportReport(ViewModel model)
{
var report = model.ReportName;
var values = model.FilterValues;
return new EmptyResult();
}
Then view's scripts will be:
#section scripts{
<script>
$(function () {
var reportName = 'ReportName';
var filterValues = [];
filterValues.push({ 'Id': 0, 'Value': 'value1' });
filterValues.push({ 'Id': 1, 'Value': 'value2' });
filterValues.push({ 'Id': 2, 'Value': 'value3' });
var model = JSON.stringify({ ReportName: reportName, FilterValues: filterValues});
$.ajax({
url: '/Home/ExportReport/',
type: 'POST',
contentType: "application/json",
data: model,
success: function () {
alert('success');
},
error: function () {
alert('failure');
}
});
});
</script>
}
Set up your model in MVC like this
public class SpecialDataModel
{
public string reportName { get; set; }
public List<SingleFilterValue> FilterValues { get; set; }
}
public class SingleFilterValue
{
public int id { get; set; }
public string value{ get; set; }
}
Set up your controller method like this
[HttpPost]
public void ExportReport(SpecialDataModel myData)
{
}
Set up your data for your ajax data property like this
var reportName= 'ReportName';
var FilterValues = [];
FilterValues.push({'id': 0, 'value': 'value1'});
FilterValues.push({'id': 1, 'value': 'value2'});
FilterValues.push({'id': 2, 'value': 'value3'});
var model = JSON.stringify({ 'reportName' : reportName, 'FilterValues' : FilterValues });
From an ajax call I get some data which I want to pass to another window in a button click. I receive the data successfully but when that data is passed, in controller methods parameter is receiving the value as null.
<script>
$(document).ready(function () {
$('#btnSalesInAmount').click(function () {
var data = {
toDate: $('#todatepicker').val(),
fromDate: $('#fromdatepicker').val(),
customerId: $('#CustomerId').val()
};
$.ajax({
type: 'Get',
url: '/Reports/SalesInAmount' + '?toDate=' + data.toDate + '&fromDate=' + data.fromDate + '&customerId=' + data.customerId,
data: data,
success: function (data) {
window.open("/Reports/SalesInAmountView" + '?salesInAmount=' + data, 'SalesInAmountViewWindow', "features");// the data is not received by controllers method
}
});
});
});
</script>
in controller
public ActionResult SalesInAmountView(SalesInAmount salesInAmount) // parameter value is null
{
return View();
}
the model
public class SalesInAmount
{
public DateTime SalesDt { get; set; }
public int SalesSl { get; set; }
public int CustomerSupplyId { get; set; }
public string CustomerSupplyNm { get; set; }
public double TotalSalesByCustomer { get; set; }
public double TotalDiscount { get; set; }
public double TotalVat { get; set; }
public double TotalSales { get; set; }
public List<SalesInAmount> List { get; set; }
}
Try this ,
Simplify Your Data Set ,
var Param1= $('#ID').val();
var Data = JSON.stringify({ Data1 : Param1, . . });
Ajax
$.ajax({
url: '#Url.Action("Action_Name", "Controller_Name")',
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
data: Data,
cache: false,
success: function (data) {
});
}, error: function (request, status, error) {
}
});
}
Controller
public JsonResult Action_Name(string Data1 , . . )
{
return Json(Some_Json);
}
Note : this Controller Return Json Result , It depends on requirement .
You need to stringify the javascript object before pass as the parameter , JSON.stringify() is the function in javascript
<script>
$(document).ready(function () {
$('#btnSalesInAmount').click(function () {
var data = {
toDate: $('#todatepicker').val(),
fromDate: $('#fromdatepicker').val(),
customerId: $('#CustomerId').val()
};
$.ajax({
type: 'Post',
url: '/Reports/SalesInAmount',
data: JSON.stringify(data),
success: function (data) {
window.open("/Reports/SalesInAmountView" + '?salesInAmount=' + data, 'SalesInAmountViewWindow', "features");// the data is not received by controllers method
}
});
});
});
Make sure you have given same name of variable as you modal class SalesInAmount.
[HttpPost]
public ActionResult SalesInAmountView(SalesInAmount salesInAmount) // parameter value is null
{
return View();
}
I want to send an object from view to controller, ajax hits the action result but data is not being delivered to action result
View:
function submit()
{
var obj = {};
obj.PD = getResult('pd');
obj.MD = getResult('md');
obj.C = getResult('c');
obj.ME = getResult('me');
obj.EE = getResult('ee');
obj.SED = getResult('sed');
obj.RT = getResult('rt');
obj.SEA = getResult('sea');
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: '{obj' + JSON.stringify(obj) + '}',
dataType: 'json',
success: function (res) {
},
error: function (msg) {
}
});
//alert(getResult('pd'));
}
Model:
public class QAViewModel
{
public string C { get; set; }
public string EE { get; set; }
public string MD { get; set; }
public string ME { get; set; }
public string PD { get; set; }
public string RT { get; set; }
public string SEA { get; set; }
public string SED { get; set; }
}
Controller:
Editing as a good point was raised:
In the post you can just pass the full object like so:
function submit()
{
var obj = {};
obj.PD = getResult('pd');
obj.MD = getResult('md');
obj.C = getResult('c');
obj.ME = getResult('me');
obj.EE = getResult('ee');
obj.SED = getResult('sed');
obj.RT = getResult('rt');
obj.SEA = getResult('sea');
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: obj,
success: function (res) {
},
error: function (msg) {
}
});
//alert(getResult('pd'));
}
If you want to stick with json then modify your ajax call accordingly (you error was in the way you were building the data property:
$.ajax({
url: '/Assessment/AssessNow',
type: 'POST',
async: false,
data: JSON.stringify({obj: obj}),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (res) {
},
error: function (msg) {
}
});
Also, depending on what you are doing with the result you may need to flip your controller actions to return JsonResult (Ignore if you are doing something such as returning a partial view to load):
[HttpPost]
public JsonResult Whatever(QAViewModel obj)
{
return Json(whatever, JsonRequestBehavior.AllowGet);
}
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'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"
});