I'm trying to post back a list of data objects (WorkOrders), in JSON format to my Webapi controller, this works amazingly well, except for the slight flaw in that the data object parameter (savemodel) is null when it hits the webapi controller.
This is a snip from the JS (slots is mock data)
var slots = [];
slots.push({ 'WorkOrder': 'XX21', 'OrderDate': '2015-10-11 00:00:00', 'Slot': '1', 'SageRef': 'HS11' });
slots.push({ 'WorkOrder': 'XX22', 'OrderDate': '2015-10-12 00:00:00', 'Slot': '2', 'SageRef': 'HS12' })
slots.push({ 'WorkOrder': 'XX23', 'OrderDate': '2015-10-13 00:00:00', 'Slot': '3', 'SageRef': 'HS13' });
console.log(JSON.stringify({ 'savemodel': slots }))
$.ajax({
type: "POST",
url: 'http://localhost:55821/api/schedule',
data: JSON.stringify({ 'savemodel': slots }),
contentType: 'application/json; charset=utf-8'
}).success(function (data) {
$scope.$apply(function () {
if (data.SaveMessage.length > 0) {
// do something
}
else {
// do something else
}
});
});
The model:
public class WorkOrderModel
{
public string WorkOrder { get; set; }
public string OrderDate { get; set; }
public string SlotNumber { get; set; }
public string SageRef { get; set; }
}
The postback method:
[HttpPost]
public IHttpActionResult UpdateWorkOrder([FromBody]List<WorkOrderModel> savemodel)
{
StringBuilder saveMessage = new StringBuilder();
foreach (WorkOrderModel model in savemodel)
{
// save the WO model object here
}
if (saveMessage.Length > 0)
{
return Ok(new { SaveMessage = "There were issues: " + saveMessage.ToString() });
}
else
{
return Ok(new { SaveMessage = "" });
}
}
Posted JSON
Null parameter in the WebApi Controller
This is driving me nuts so any help will be hugely appreciated at this stage!
Regards,
itsdanny
Sorted, it changed
data: JSON.stringify({ 'savemodel': slots}),
to
data: JSON.stringify(slots),
Related
I have read a lot of questions regarding similar issues, but none of them seems to work for me.
I am receiving null for the movie object in the post action method.
This is my controller:
public class MovieController : Controller
{
[Route("movies/all")]
[HttpGet]
public ActionResult All()
{
List<string> movies = new List<string>();
movies.Add("Some Movie");
movies.Add("Diamond Team");
//Get movies
return Ok(movies);
}
[Route("movies/post")]
[HttpPost]
public ActionResult Post([FromBody] Movie movie)
{
Console.WriteLine(movie);
List<string> movies = new List<string>();
movies.Add(movie.title);
//Get movies
return Ok(movies);
}
public ActionResult Index()
{
return View();
}
}
This is the Movies class:
public class Movie
{
public string title { get; set; }
public float rating { get; set; }
public int year { get; set; }
public Movie(string title,float rating, int year)
{
this.title = title;
this.rating = rating;
this.year = year;
}
public Movie()
{
}
}
This is the post request (using postman), I have tried either application/json and application/json; charset=utf-8 as the Content-Type but in both cases I have received null for the movie object:
{
"title":"Some Movie",
"rating":"1.87",
"year":"2011"
}
Postman screenshots:
How can I fix this?
Please try to change your request JSON to this:
{
"title":"Some Movie",
"rating":1.87,
"year":2011
}
Your model must first be serialized and then passed to data in ajax call. this is one sample, You have to change the model according to your needs....
$("#btnPost").click(function() {
var employee = new Object();
employee.Name = $('#txtName').val();
employee.Address = $('#txtDesignation').val();
employee.Location = $('#txtLocation').val();
if (employee != null) {
$.ajax({
type: "POST",
url: "/JQueryAjaxCall/AjaxPostCall",
data: JSON.stringify(employee),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
if (response != null) {
alert("Name : " + response.Name + ", Designation : " + response.Designation + ", Location :" + response.Location);
} else {
alert("Something went wrong");
}
},
failure: function(response) {
alert(response.responseText);
},
error: function(response) {
alert(response.responseText);
}
});
}
});
in the postman you can use different way to call method. Click on code button and choose one of way to call method.
you can use jquery and put code onto section....
I am having a hard time posting a list of arrays from my view to the controller. Every other value is coming through.
Can someone spot what is wrong with my code?
Controller:
public ActionResult SaveProgress(BBCRMSurveyVM model)
{
try
{
return Json(new { success = true });
}
catch (Exception e)
{
return Json(new { success = false, msg = e.Message });
}
}
Main view model:
public string ImplementationProcessFeelWasSuccessful { get; set; }
public string ImplementationProcessAdviceOtherFederations { get; set; }
public List<AdditionalTechnologyVM> AdditionalTech = new List<AdditionalTechnologyVM>();
AdditionalTechVM:
public class AdditionalTechnologyVM
{
public string PlatformName { get; set; }
public string BusinessPurpose { get; set; }
public bool? FullyIntergrated { get; set; }
public bool? PartiallyIntergrated { get; set; }
}
JS file:
function onAddButtonClickEvent() {
additionaltechs.push({
'PlatformName': platformNameAT,
'BusinessPurpose': businessPurposeAT,
'FullyIntergrated': intergrated == "Fully" ? true : false,
'PartiallyIntergrated': intergrated == "Partially" ? true : false
});
}
function SaveProgress() {
var formData = $('#wizard').serializeArray();
//if (additionaltechs.length > 0) {
// for (var x = 0; x < additionaltechs.length; x++) {
// formData[formData.length] = { name: "AdditionalTech", value: JSON.stringify(additionaltechs[x]) };
// }
//}
formData[formData.length] = { name: "AdditionalTech", value: additionaltechs };
$.each(formData, function (index, field) {
if (field.name.search('Budget') > 0) {
field.value = field.value.replace('$', '').replace(/,/g, '');
}
});
formData = JSON.stringify(formData);
console.log(formData);
$.ajax({
url: '/save-progress',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: formData,
dataType: 'json',
success: function () {},
error: function () {}
});
}
The output in the console:
The list count is always 0?
I think you made this more complicated than you needed it to be. :)
Ultimately, it looks like your controller method is taking a single model, not an array. Thus, I would suspect to see the JSON you send look like this:
{
"ImplementationProcessFeelWasSuccessful" : "",
"ImplementationProcessAdviceOtherFederations" : "",
"AdditionalTech" : [...]
}
If it should be a single item being sent, then I'd expect your code to be like this:
function SaveProgress() {
var formData =
{
ImplementationProcessFeelWasSuccessful : $('#wizard #val1').val(),
ImplementationProcessAdviceOtherFederations : $('#wizard #val2').val(),
AdditionalTech : additionaltechs
};
formData = JSON.stringify(formData);
console.log(formData);
$.ajax({
url: '/save-progress',
contentType: 'application/json; charset=utf-8',
type: 'POST',
data: formData,
dataType: 'json',
success: function () {},
error: function () {}
});
}
However, you are sending an array of items up and that makes no sense here.
Ended up sending the list as a JSON string & receiving it also as a string. In the controller I using the JsonConvert.DeserializeObject method like this:
var additionalTechs = JsonConvert.DeserializeObject<List<AdditionalTechnologyVM>>
(model.AdditionalTech);
I have method to add data to db on Aajax request
Here is code on back-end
public ActionResult AddingInternalAppointment(string Start, string End, string Title, DateTime Date,int id)
{
using (var ctx = new ApplicationDbContext())
{
Appointment appointmentInt = new Appointment()
{
Start_appointment = Start,
End_appointment = End,
Title = Title,
Type_of_appointment = "Internal",
Date = Date
};
ctx.Appointments.Add(appointmentInt);
ctx.SaveChanges();
return Json(new {Result = "Success", Message = "Saved Successfully"});
}
}
And here is AJAX request on front - end:
function addAppointmentInternal() {
var idofdoctor = moment($('#startAppointment').val()).toISOString();
alert(idofdoctor);
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
Start: $('#startAppointment').val(),
End: $('#endAppointment').val(),
Title: $('#title').val(),
Date: moment($('#startAppointment').val()).toISOString()
},
url: '#Url.Action("AddingInternalAppointment","Calendar")',
success: function (da) {
if (da.Result === "Success") {
$('#calendar').fullCalendar('refetchEvents');
$("#myModal2").modal();
} else {
alert('Error' + da.Message);
}
},
error: function(da) {
alert('Error');
}
});
}
When I call this function it show me this error, but I have values in Date.
How I can fix this?
Try changing parameter name Date to something else (like appointmentDate). You need to change same in ajax call.
A few things.
Create a model for the Action
public class AppointmentOptions {
public string Start { get; set;}
public string End { get; set;}
public string Title { get; set;}
public DateTime Date { get; set;}
public int Id { get; set;}
}
Update the action accordingly
[HttpPost]
public ActionResult AddingInternalAppointment([FromBody]AppointmentOptions model) {
if(ModelState.IsValid) {
string Start = model.Start;
string End = model.End;
//...
//...code removed for brevity
}
Next on the client update ajax call
function addAppointmentInternal() {
var idofdoctor = moment($('#startAppointment').val()).toISOString();
var model = {
Start: $('#startAppointment').val(),
End: $('#endAppointment').val(),
Title: $('#title').val(),
Date: moment($('#startAppointment').val()).toISOString()
};
alert(idofdoctor);
$.ajax({
type: 'Post',
dataType: 'Json',
data: JSON.stringify(model), //<-- NOTE
url: '#Url.Action("AddingInternalAppointment","Calendar")',
success: function (da) {
if (da.Result === "Success") {
$('#calendar').fullCalendar('refetchEvents');
$("#myModal2").modal();
} else {
alert('Error' + da.Message);
}
},
error: function(da) {
alert('Error');
}
});
}
I have a project in .Net for school.
I try to send a POST json through ajax a MVC controller 5. I reached the correct function of the controller but it received values are 0 or null:
values in controller are 0 or null
Despite that variables are properly filled the browser console:
variables in browser console
Where does the fault do you think?
Here are some code :
Function that call controller :
function GeneratePDF() {
var dataToSend;
var age = 69;
instruction = "trololololoCOCO";
dataToSend = JSON.stringify({ item: { distance: age, instruction: instruction } });
console.log("dataToSend : " + dataToSend);
var uri = '/GeneratePDF/Print';
$.ajax({
type: 'POST',
url: uri,
data: dataToSend,
contentType: "application/json; charset=utf-8",
})
.done(function (data) {
console.log('pdf controller DONE');
})
.fail(function (jqXHR, textStatus, err) {
console.log(jqXHR);
$("#result").html(jqXHR.responseText);
});
}
Controller :
[HttpPost]
public ActionResult Print(test item)
{
//something
return new Rotativa.ActionAsPdf("ViewPrint",new { id = item }) { FileName = "Cartographie.pdf" };
}
Model :
public class test
{
public int distance;
public string instruction;
public test(int distance, string instruction)
{
this.distance = distance;
this.instruction = instruction;
}
}
Fields are not allowed.
Your model declaration must have get and set properties:
public int distance { get; set; }
public string instruction { get; set; }
I can't figure out why my action param is coming through null. I'm also not sure of how to even diagnose the issue. I can see the http request data being sent with data and stepping through the debugger shows the object as null, not sure how to see the steps in between.
Models
public class ComplexObj
{
public int Id { get; set; }
public int Test1 { get; set; }
public decimal Test2 { get; set; }
}
public class BiggerObj
{
public BiggerObj()
{
ComplexObj = new List<ComplexObj>();
}
public long OtherId { get; set; }
public string Name { get; set; }
public ICollection<ComplexObj> ComplexObjs { get; set; }
}
Action
[HttpPost]
public void TestAction(BiggerObj[] biggerObjs)
{
...// biggerObjs is null :(
}
View
function ajaxCall() {
var data = [];
var bigObj = new Object();
bigObj.OtherId = 123;
bigObj.Name = "TestName";
bigObj.ComplexObj = [];
var complexObj = new Object();
complexObj.Id = 789;
complexObj.Test1 = 123;
complexObj.Test2 = 456;
bigObj.ComplexObj.push(complexObj);
data.push(bigObj);
}
}
$.ajax({
url: SITEROOT + "myController/TestAction",
cache: false,
type: 'POST',
data: data,
complete: function() {
alert('done');
}
});
}
Solved
You must use:
JSON.stringify and declare the contentType as "application/json; charset=utf-8"
Parse the decimal value by using parseFloat() function, decimal is considered as int by default binder.
Change your Action to this:
[HttpPost]
public ActionResult TestAction(BiggerObj[] biggerObjs)
{
...// biggerObjs is null :(
}
Change your ajaxCall function to this:
//ajaxCall
function ajaxCall() {
var data = [];
var bigObj = {
OtherId : 123,
Name : "TestName",
ComplexObjs : new Array()
};
var ComplexObjs = {
Id: 789,
Test1: 123,
Test2: parseFloat(456)
// decimal types are considered an integer, you have to parse
};
bigObj.ComplexObjs.push(ComplexObjs);
data.push(bigObj);
$.ajax({
url:"/Test/TestAction",
cache: false,
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
complete: function () {
alert('done');
}
});
}
I tested, works fine.