Passing data array from Javascript to C# - c#

This is my class ARecipe :
public class ARecipe
{
public string picture { get; set; }
public string title { get; set; }
public int cookingTime { get; set; }
public int preparationTime { get; set; }
public string IngredientList { get; set; }
public string ingredientsDescription { get; set; }
public int nbPersons { get; set; }
public string Category { get; set; }
public string difficulty { get; set; }
public double nbStars { get; set; }
}
My Ajax call :
var dico = {
picture: $("#fakeInput").val(),
title : $("#title").val(),
cookingTime : $("#cookingTime").val(),
preparationTime : $("#preparationTime").val(),
IngredientList : $("#ingredientListArea").val(),
ingredientsDescription : $("#preparationArea").val(),
nbPersons : parseInt($("#select-nb-Persons").val()),
Category : $("#select-category").val(),
difficulty: $("#select-difficulty").val(),
nbStars : 4
};
$.ajax({
url: "/AddRecipe/TempData",
type: 'POST',
success: function (e) {
//success event
},
///Form data
data: JSON.stringify(dico),
///Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
And the method receiving the datas :
[HttpPost]
public ActionResult TempData(ARecipe recipe) {
return Json("");
}
My Ajax call well go to the TempData method but when I analyse the parameter 'recipe' with the debugger, I notice that all the fields are 'null'.
Why ?
Do you have a solution ?
Thank you

You are sending the data as JSON, but the server expects is as regular POST data. Just let the ajax method turn it into a regular POST request instead of forcing it into JSON:
///Form data
data: dico,

Just Correct these issues :
$.ajax({
url: "/AddRecipe/TempData",
type: 'POST',
dataType: 'json',
contentType: 'application/json',
success: function (e) {
//success event
},
///Form data
data: JSON.stringify(dico),
///Options to tell JQuery not to process data or worry about content-type
cache: false,
});
[HttpPost]
public JsonResult TempData(ARecipe recipe) {
return Json("");
}

Related

Ajax call data is not being passed to the controller during a POST

Background: I have a jQuery Kendo data grid where I am allowing users to do batch update functionality. I am attempting to call my controller through an AJAX call in jQuery. The issue I am facing is that my model never gets passed to the controller method. When my breakpoint hits on Controller it comes with count of 0 with MyModel items. Even though I can see my model in Fiddler body of request it actually never makes it to the controller. This issue doesn't come up when I hit the API directly through Fiddler even when I pass in the same model which the application generates. What am I missing ? I am leaning towards something wrong with my AJAX request.
Below is my controller code:
[HttpPost]
[Route("UpdateRequest")]
[ResponseType(typeof(List<MyModel>))]
public HttpResponseMessage UpdateRequest([FromBody] List<MyModel> items)
{
var p = new GridItemProcessor();
var r = p.UpdateRows(items);
return Request.CreateResponse(HttpStatusCode.OK, r);
}
Below is my ajax call code:
$.ajax({
type: "POST", async: false, url: baseAPIURL + "MrrRequest/UpdateRequest",
timeout: 15000,
dataType: 'json',
cache: false,
data: {
items: JSON.stringify(options.data.models)
},
success: function (result) {
options.success(result);
return true;
},
complete: function (data) {
$("#myGrid").data("kendoGrid").dataSource.read();
},
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
options.error();
}
});
Below is how my json request looks like
[
{
"RequestId": 40,
"beneClaimId": 32,
"claimId": "20211308068186",
"lineCnt": "1",
"medRecRequested": true,
"eobChk": true,
"clmChk": true,
"dateReceived": null,
"MedRecRcvd": {
"MedRecRcvdId": "I",
"MedRecRcvdName": "Incomplete"
}
}
]
Below is what MyModel looks like
public class MyModel
{
public int RequestId { get; set; }
public int beneClaimId { get; set; }
public string claimId { get; set; }
public string lineCnt { get; set; }
public bool? medRecRequested { get; set; }
public bool? eobChk { get; set; }
public bool? clmChk { get; set; }
public string dateReceived { get; set; }
public ViewModel.MedRecRcvd MedRecRcvd { get; set; } = new MedRecRcvd();
}
public class MedRecRcvd
{
public string MedRecRcvdId { get; set; }
public string MedRecRcvdName { get; set; }
}
Your controller expects a collection of MyModel. Therefore you need to post an array of items. By using stringify you are posting a single string. As a test, if you changed your controller to accept 'string items' you should get a value in the controller.
Assuming your options.data.models is an array, you would post:
items: options.data.models
The properties on each item in that array need to match those on MyModel on the server. If that is the case, your posted data should materialise in the controller.

JQUERY ajax posts JSON to C# MVC controller, but the incoming data is null

I have a strange problem. I have a C# data structure with two classes:
public class AddQuestionModel2
{
public int? QuestionID { get; set; }
public string QuestionString { get; set; }
public int? TrueAnswer { get; set; }
public QuestionType Type { get; set; }
public IEnumerable<AddQuestionModelAnswer> Answers { get; set; }
}
public class AddQuestionModelAnswer
{
public int? ID { get; set; }
public string AnswerString { get; set; }
public bool? IsRight { get; set; }
public int? Order { get; set; }
}
public enum QuestionType
{
SingleSelect,
MultiSelect,
OrderAnswers,
FillingGap,
ExampleRequired,
TrueOrFalse
}
The javascript generates the javascript object (which looks fine for the data structure) and JSON.stringify translates to the following json string:
{"QuestionString":"<p>Question 1</p>","TrueAnswer":"0","Type":"0","Answers":[{"AnswerString":"<p>Answer 1</p>","IsRight":"0"},{"AnswerString":"<p>Answer 2</p>","IsRight":"0"},{"AnswerString":"<p>Answer 3</p>","IsRight":"0"},{"AnswerString":"<p>Answer 4</p>","IsRight":"0"}]}
The json data is sent by the following jquery command:
$.ajax({
url: "/Questions/Add",
method: "POST",
async: true,
dataType: "json",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
success: function (e) {
if (e.Success) {
document.location = "/Questions";
}
},
error: function (e) {
var i;
for (i in e) {
console.log(e[i]);
}
}
});
On the C# side, I have the following method to receive the post data:
[HttpPost]
public async Task<string> Add([FromBody] AddQuestionModel2 q)
{
var ctx = this.HttpContext;
JsonResultModel res = new JsonResultModel();
}
The parameter "q" is always null. If I expand ctx (HttpContext), the Request.Form data is threw System.InvalidOperationException.
Does any if you have any idea what could be wrong?
The biggest problem is that I am unable to debug what is happening within HttpContext and why it is throwing exception.
Thanks in advance!
Gabor
In you ajax code try data:data, instead of data: JSON.stringify(data). The JSON.stringify() method converts a JavaScript object or value to a JSON string, but ajax data need JavaScript object. Another things to try instead of 0 or 1 use "true" or "false" in your bool fields.
In the postman everything works.

Asp.Net how to retrieve JSON from jQuery

I have created a JSON in jQuery which looks like this:
{
"objects":[
{
"ObjectId":1,
"Line1":"Software",
"Line2":"Microsoft",
"Line3":"Web",
"Line4":"Asp.Net",
"Line5":"jQuery"
},
{
"ObjectId":2,
"Line1":"Hardware",
"Line2":"Microsoft",
"Line3":"Computer",
"Line4":"Surface",
"Line5":"Pro"
}
]
}
Now I use AJAX to send it via jQuery to my controller:
var postData = { objects: objectArray };
// Fire off the request to controller
$.ajax({
cache: false,
url: '/Controller/myAction',
type: "POST",
dataType: 'html',
data: postData,
success: function (result) {
// success handler
}
})
public ActionResult myAction(???)
{
return view();
}
What I am not sure about is how I receive the object in my controller. Can someone help me with this please.
Thanks in advance!
Just a little lifehack for future: if you have to add new class based on existing JSON or XML model, there are awesome built-in tool in Visual Studio:
Class generating from JSON/XML models
This should work, start by creating a model object to represent the data on the server side
public class ObjectModel
{
public string ObjectId { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string Line4 { get; set; }
public string Line5 { get; set; }
}
Then define your mvc actions parameter like this
[HttpPost]
public ActionResult myAction(List<ObjectModel> objects)
{
return view();
}
then simply pass the object array as json
// Fire off the request to controller
$.ajax({
cache: false,
url: '/Controller/myAction',
type: "POST",
contentType: "application/json",
dataType: 'json',
data: JSON.stringify(objectArray),
success: function (result) {
// success handler
}
})

Ajax data into MVC model

Our very simple models:
public class OrderSubmissionProductViewModel
{
public int Id { get; set; }
public decimal Price { get; set; }
public int Qty { get; set; }
}
public class OrderSubmissionViewModel
{
public int CustomerId { get; set; }
public int AccountId { get; set; }
public OrderSubmissionProductViewModel[] Products { get; set; }
}
The AJAX:
$.ajax({
url: self.urlSubmitOrder,
data: JSON.stringify({ submission: submission }),
type: 'POST',
success: function () { alert("Submitted"); },
fail: function () { alert("Failed"); }
});
The MVC controller has this method signature:
public ActionResult SubmitAdminOrder(OrderSubmissionViewModel submission)
{ ... }
This is what the POST looks like:
{"submission":{"CustomerId":43,"AccountId":"20000","Products":[{"Id":4,"Price":100,"Qty":1},{"Id":6,"Price":14,"Qty":1}]}}
I can hit a breakpoint in the controller method, and the model is not null, but all of its properties are default values. It's not getting bound correctly. What am I doing wrong?
We're using ASP.Net MVC 4.
Make sure the submission object isn't empty and can you try adding a contentType to the ajax options?
$.ajax({
url: self.urlSubmitOrder,
data: JSON.stringify({ submission: submission }),
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function () { alert("Submitted"); },
fail: function () { alert("Failed"); }
});
Or take a look at this post Pass viewmodel with two objects to controller using Json

strange issue passing a JSON object to c# method (with a collection as a parameter (using JQuery Widgets)

I'm facing a strange issue when passing the following:
queueNotificationData = {
StartDate: that.batchData.StartDate.valueOf(),
StartTime: that.batchData.StartTime.valueOf(),
EndDate: that.batchData.EndDate.valueOf(),
EndTime: that.batchData.EndTime.valueOf(),
ETR: that.batchData.ETR.valueOf(),
PTW: that.batchData.PTW.valueOf(),
SelectedTemplate: that.batchData.SelectedTemplate.valueOf(),
IncidentFlag: that.batchData.IncidentFlag.valueOf(),
IncidentNumber: that.batchData.IncidentNumber.valueOf(),
SendToSubscriber: that.batchData.SendToSubscriber.valueOf(),
SendToCustomer: that.batchData.SendToCustomer.valueOf(),
SendToSMC: that.batchData.SendToSMC.valueOf(),
BatchServiceIds: that.serviceIds,
DescriptionOfWorks: that.batchData.DescriptionOfWorks.valueOf(),
AffectedCustomerVOs: that.customerVOs
}
The issue is with the AffectedCustomerVOs parameter - this is retrieved from an earlier call and is passed through a series of widgets (it's part of a pretty long wizard form)
This is the code that calls the c# method to actually do the processing:
this.options.sendRequest({
url: this.options.dataUrl,
data: queueNotificationData,
cache: false,
dataType: 'json',
success: function (data) {
that.data = data;
that._showSavedMessage();
},
error: function () {
that._showErrorMessage();
}
});
and here is the c# method:
[HttpPost]
[Authorize]
[ValidateInput(false)]
public JsonResult QueueNotificationBatch(QueueNotificationInputModel param)
{
//do some work - code not included
}
where QueueNotificationInputModel is
public class QueueNotificationInputModel
{
public string BatchServiceIds { get; set; }
public List<CustomerVO> AffectedCustomerVOs { get; set; }
public string StartDate { get; set; }
public string StartTime { get; set; }
public string EndDate { get; set; }
public string EndTime { get; set; }
public string ETR { get; set; }
public string PTW { get; set; }
public string SelectedTemplate { get; set; }
public string IncidentFlag { get; set; }
public string IncidentNumber { get; set; }
public bool SendToSubscriber { get; set; }
public bool SendToCustomer { get; set; }
public bool SendToSMC { get; set; }
public string DescriptionOfWorks { get; set; }
public QueueNotificationInputModel()
{
AffectedCustomerVOs = new List<CustomerVO>();
}
}
Now - all this code seems to work fine - the C# method is successfully called and the values passed in are good except for AffectedCustomerVOs. The list has 3 items in it (this is correct) but the items within the list have no values - all nulls/0's. If I put alert(that.customerVOs[0]['Email']); immediately before creating the queueNotificationData object, it correctly displays "test#test.com" but this value never makes it into the c# method.
I assume it's some sort of serialization problem but I can't figure out where? Help would be much appreciated
Try sending this complex object as JSON serialized:
this.options.sendRequest({
url: this.options.dataUrl,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(queueNotificationData),
cache: false,
dataType: 'json',
success: function (data) {
that.data = data;
that._showSavedMessage();
},
error: function () {
that._showErrorMessage();
}
});
The JSON.stringify method shown here is natively built in modern browsers. If you need to support legacy browsers you might need to include the json2.js script to your page.

Categories

Resources