Send Post Data to Controller with Ajax [Project .Net] - c#

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

Related

jQuery Array is not posting to ASP.NET MVC controller

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

The parameters dictionary contains a null entry for parameter (ASP.NET)

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

Webapi parameter is null on Method

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),

Passing an object to MVC controller method in AJAX success using window.location

Ajax call -
$.ajax({
type: "POST",
url: configMap.sitePath + "api/Quiz/" + quizResponse.quizId,
data: JSON.stringify(quizResponse),
success: function(data) {
var resultid = data.data.quizInstanceId;
var resultresponse = data.data;
window.location.href = "supply-chain-pressure/ScptResult/" + resultresponse;
}
controller Method -
public ActionResult ScptResult(QuizResult resultresponse)
{
// Do something
return View();
}
Route -
routes.MapRoute(
name: "SupplyChainPressureResult",
//url: "supply-chain-pressure/ScptResult/{resultid}",
url: "supply-chain-pressure/ScptResult/{resultresponse}",
defaults: new { controller = "SupplyChainPressure", action = "ScptResult" }
);
class -
public class QuizResult
{
public int quizInstanceId { get; set; }
public string WeakestLinkCode { get; set; }
public string WeakestLinkDescription { get; set; }
public decimal PercentageOfUsers { get; set; }
public IEnumerable<OverallResult> OverallResults { get; set; }
}
But For some reason the resultresponse is null in the controller method. Can someone help please . We need to pass data.data (resultresponse) to the controller Method.
Thanks Every one for the Help . I only using one parameter and then redirecting to a controller methods which does the stuff for me -
$.ajax({
type: "POST",
url: configMap.sitePath + "api/Quiz/" + quizResponse.quizId,
data: JSON.stringify(quizResponse),
success: function (data) {
var resultId = data.data.quizInstanceId;
window.location.href = configMap.sitePath + 'Result-Display/Index/' + resultId;
},

asp mvc controller receiving null values from ajax

have tried the methods found but still cannot seem to tackle the issue.
am passing a list of object via Jquery Aja but it seems that the controller is receiving null values (it is recognizing the list count fine).
the jquery code is as follows:
var xmlids = Array();
for (var i = 0; i < orderId.length; i++) {
var xdata = {
"XmlOid": "" +orderId[i] + "",
"CourierCompany": $("#CourierCompany_"+orderId[i]).val() ,
"CourierService": $("#CourierService_" + orderId[i]).val(),
"StoreId" : storeId
};
xmlids.push(xdata);
}
var data = { invoices: xmlids };
$.ajax({
url: purl,
type: "POST",
dataType: "json",
//contentType: "application/json;",
async: false,
data: data,
The controller param is :
public JsonResult ProcessSaleOrder(List<XMLInvoiceGeneration> invoices)
the object is as follows:
public class XMLInvoiceGeneration
{
public Int64 XmlOid { get; set; }
public string CourierCompany { get; set; }
public string CourierService { get; set; }
public Int64? StoreId { get; set; }
}
any help appreciated.
I tried to replicate your problem.
I created a new ASP.NET MVC web application, and in the Home controller's Index view, I added the following
<input type="button" id="send" value="Send" />
#section scripts{
<script type="text/javascript">
$(function () {
$("input#send").on("click", function () {
var xmlids = Array();
for (var i = 0; i < 2; i++) {
var xdata = {
"XmlOid": 1,
"CourierCompany": "TempData",
"CourierService": "Temp",
"StoreId": 2
};
xmlids.push(xdata);
}
var data = { invoices: xmlids };
$.ajax({
url: "/Home/ProcessSaleOrder",
type: "POST",
dataType: "json",
async: false,
data: data
});
});
})
</script>
}
I basically created some temp data, but trying to still use your original idea. My controller looks like this:
[HttpPost]
public ActionResult ProcessSaleOrder(List<XMLInvoiceGeneration> invoices)
{
return new EmptyResult();
}
When I click the button, and hit the breakpoint in the controller, the invoices parameter contains 2 items, both with the values I set in the JavaScript code. I'm not sure why your code isn't working, but maybe you can use mine as a template to help you narrow down what the issue is.
Try this
uncomment //contentType: "application/json;",
And send data with JSON.stringify(data)
data: JSON.stringify(data)
PS: Best practice for url : url: "#Url.Action("method","controller")"
I had the same issue on sending a List to the controller. After a lot of effort, I found the reason why it is sending as null. It's the fields with Return Type(Class) that are not added with {get; set; }
$.ajax({
url: "/Home/CreateTasks",
data: ko.toJSON({Id: this.Id, tasks: objList }),
type: "POST",
dataType: "json",
processData: true,
contentType: "application/json; charset=utf-8",
success: data => {
}
And my Model Class is:
After
public class TaskFields
{
public string Title { get; set; }
public string Activity { get; set; }
}
public class CreateTaskInput
{
public int Id { get; set; }
public TaskFields TaskProperties { get; set; }
}
Before it was:
public class TaskFields
{
public string Title;
public string Activity;
}
public class CreateTaskInput
{
public int Id;
public TaskFields TaskProperties;
}
And My Controller Method is:
[HttpPost]
public JsonResult MethodName(int Id, List<CreateTaskInput> tasks)
{
}
I am not sure this answer will help you. But it may help someone who has a similar mistake. Thanks!
Add [FromBody] to the parameters in action
[HttpPost]
public ActionResult ProcessSaleOrder([FromBody] List<XMLInvoiceGeneration> invoices)
{
return new EmptyResult();
}

Categories

Resources