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);
}
Related
When I set a breakpoint on LoadReport, every parameter is null. For some reason the values are not binding to the parameters with the same name.
Javascript/AJAX
$('#savedCriteria').on('change', function () {
var criteriaSelected = $('#savedCriteria option:selected').text();
var data = { actionName: "Daily", reportInput: "ReportDaily", reportCriteria: criteriaSelected };
//Ajax form post
$.ajax({
type: 'POST',
data: data,
contentType: "application/json; charset=utf-8",
url: '#Url.Action("LoadReport", ViewContext.RouteData.Values["Controller"].ToString())',
success: function (data) {
if (data.success) {
alert("Test");
} else {
alert("Test Not Successful");
}
}
});
});
Controller
public void LoadReport(string actionName, string reportInput, string reportCriteria)
{
var reportObject = Activator.CreateInstance(Type.GetType(reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(reportInput);
RedirectToAction(actionName, "Reports", reportList.Where(x => x.CriteriaName == reportCriteria));
}
Default method type is HttpGet, you need to set it to HttpPost.
[HttpPost]
public void LoadReport(string actionName, string reportInput, string reportCriteria)
{
var reportObject = Activator.CreateInstance(Type.GetType(reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(reportInput);
RedirectToAction(actionName, "Reports", reportList.Where(x => x.CriteriaName == reportCriteria));
}
Also keep in mind that with your ajax call you can not use RedirectToAction. You need something like this:
[HttpPost]
public ActionResult LoadReport(string actionName, string reportInput, string reportCriteria)
{
var reportObject = Activator.CreateInstance(Type.GetType(reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(reportInput);
Return Json(Url.Action(actionName, "Reports", reportList.Where(x => x.CriteriaName == reportCriteria));
}
And in your ajax call:
success: function (data) {
window.location.href = data;
}
UPDATE: you also need to create a POCO object and add that to the HttpPost method as parameter instead of separate parameters. Also [FromBody] attribute is needed.
POCO:
public class Data
{
public string actionName { get; set; }
public string reportInput { get; set; }
public string reportCriteria { get; set; }
}
Controller:
[HttpPost]
public JsonResult LoadReport([FromBody]Data data)
{
var reportObject = Activator.CreateInstance(Type.GetType(data.reportInput));
IEnumerable<Test.Reports.Utilities.ReportCriteria> reportList = getReportCriteria(data.reportInput);
return Json(Url.Action(data.actionName, "Reports"));
}
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 am trying to call a controller function in MVC called UpudateFingerprintStatus from my jquery script. This is a PUT call because i'm updating the status of the desired object. I'm getting a 404 error when i'm trying to call this method.
Here is my JS code:
function updateStatus(statusId, fingerprintId, isDeleted, userId) {
var confirm = window.confirm("Are you sure you wish to change the Fingerprint Status?");
if (confirm) {
$.ajax({
type: "POST",
url: "/Tools/FingerprintTool/UpdateFingerprintStatus",
dataType: "json",
processData: false,
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
userId: userId,
statusId: parseInt(statusId),
fingerprintId: fingerprintId,
isDeleted: isDeleted
}),
sucess: function(resp) {
alert("success");
},
error: function(resp) {
alert("Failure" + resp.description);
}
});
}
}
And here is my Controller method:
[HttpPut]
public JsonResult UpdateFingerprintStatus(int userId, int statusId, int fingerprintId, int isDeleted)
{
var response = _driver.UpdateFingerprintGrantById(userId, fingerprintId, isDeleted, statusId);
return Json(response.Note);
}
Any help would be greatly appreciated!
When we send post , put request it sends complex data type in body so to bind that complex data you need to create class in which all properties should have same name as you sending from front-end.
public class FingerprintStatus{
public string UserId { get; set; }
public int StatusId { get; set; }
public int FingerprintId { get; set; }
public bool IsDeleted { get; set; }
}
[HttpPut]
public JsonResult UpdateFingerprintStatus(FingerprintStatus model)
{
var response = _driver.UpdateFingerprintGrantById(model.UserId, model.FingerprintId, model.IsDeleted, model.StatusId);
return Json(response.Note);
}
This should work:
function updateStatus(statusId, fingerprintId, isDeleted, userId) {
var confirm = window.confirm("Are you sure you wish to change the Fingerprint Status?");
if (confirm) {
var domain = window.location.protocol + "//" + window.location.host;
var url = domain + "/Tools/FingerprintTool/UpdateFingerprintStatus";
var dataContract = {
userId: userId,
statusId: parseInt(statusId),
fingerprintId: fingerprintId,
isDeleted: isDeleted
};
$.ajax({
type: "PUT",
url: url,
dataType: "json",
data: dataContract,
sucess: function(resp) {
alert("success");
},
error: function(resp) {
alert("Failure" + resp.description);
}
});
}
}
[HttpPut]
public JsonResult UpdateFingerprintStatus(int userId, int statusId, int fingerprintId, int isDeleted)
{
var response = _driver.UpdateFingerprintGrantById(userId, fingerprintId, isDeleted, statusId);
return Json(response.Note);
}
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"
});
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