Format JSon so that mvc4 controller method can parse it - javascript

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

Related

.Net core - Ajax post does not pass variables to controller method

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"));
}

Cannot pass a object to a controller method with popup

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();
}

Passed Json is not accepted by controller

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"
}

how to pass variable to property of model in mvc

I have a Model as below:
public class Class1
{
public int Id { get; set; }
public DateTime Start { get; set; }
}
and I have an ActionResult which is like this:
public ActionResult Create(Class1 model)
{
...
}
now, I want to fill Start property from another external javascript file using ajax like this:
$.ajax({
url: "/Admin/Create",
dataType: "Json",
type: "Post",
data: Start:"..."
});
How can I access to another View TextBox and fill that using ajax? What should I do in data on ajax?
Please try below code:-
var model = { Name :"Shyju",
Location:"Detroit",
Interests : ["Code","Coffee","Stackoverflow"]
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: url,
contentType: "application/json"
}).done(function (res) {
$("#SomeDivToShowTheResult").html(res);
});
public class DashboardViewModel
{
public string Name {set;get;}
public string Location {set;get;}
public List<string> Interests {set;get;}
}
[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
return PartialView("_IndexPartial",m);
}

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"
});

Categories

Resources