I have the following json object, sorry for the image;
The jquery code I have looks like this;
var data = {
table: table,
favour: $("[name='radFavour']:checked").val(),
data: jsonObj
};
$.ajax({
url: appDomain + "/Compare/Ajax_Update",
type: "post",
dataType: "json",
data: data
});
The c# code looks like;
[HttpPost]
public void Ajax_Update(CompareFVM fvm)
{
}
The FVM contains a string for table and for favour and the data for those two properties comes through.
For "data" I have the following in the FVM;
public List<CompareItem> data { get; set; }
And the item;
public class CompareItem
{
public int prodId { get; set; }
public int stageId { get; set; }
public string value { get; set; }
public string property { get; set; }
}
The List has the correct amount of elements in it, in this case two, but each of them has nulls set.
So the data I am posting back is not coming through for the array elements but it is for the single fields.
Any ideas?
while ajax calling, pass the objectname as 'fvm'(name should be matching with the C# code parameter). also, please check passing json abject using JSON.stringify(data).
var fvm = {
table: table,
favour: $("[name='radFavour']:checked").val(),
data: jsonObj
};
$.ajax({
url: appDomain + "/Compare/Ajax_Update",
type: "post",
dataType: "json",
data: JSON.stringify(fvm)
});
Just basing off what similar things I've done in the past, I'd structure your code like so:
// if your C# is
public void Ajax_Update(CompareFVM fvm) {
}
// then your ajax call should be along the lines of
$.ajax({
data : {
'data' : [
{ /* compareItem */ },
{ /* compareItem */ },
// ...
]
}
})
The thing being, your C# endpoint is expecting an object, so you should give it a JSON object.
If your C# class is
public class CompareFVM {
public IList<CompareItem> data { get;set; }
}
then your corresponding JSON should be:
{ 'data' : [] }
where .data would be an array of CompareItem objects.
e.g.
{
'data' : [
{'prodId':'3175','stageId':'19045','value':'TUE','property':'despatchDay'},
{'prodId':'3175','stageId':'19045','value':'TUE','property':'despatchDay'}
]
}
Related
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.
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
}
})
EDIT: I am able to pass some plain data if I use type: 'GET' in the ajax call and [HttpGET] in the Controller.
However, complex datatypes like my Summary class is still not working and everything is either 0 or NULL.
I have the following class:
public class Summary
{
public int Total { get; set; }
public double Average { get; set; }
public int Issues { get; set; }
public int Fixed { get; set; }
public double FixedPercentage { get; set; }
public double TotalPercentage { get; set; }
public List<Issues> IssuesList { get; set; }
}
public class Issues
{
public string Name {get; set;}
public int Code {get; set;}
}
And the following Action on my Controller:
[HttpGet]
public IActionResult GetSummary(Summary summaryBySource)
{
Json(new
{
summary = "hi"
});
}
Lastly, this is the ajax call I am using to return the object to the Controller:
$.ajax({
type: 'GET',
dataType: 'json',
url: '/Summary/GetSummary/',
data: JSON.stringify(summaryBySource),
error: function (xhr) {
alert("Wrong");
},
success: function (result) {
alert("Yeah");
},
async: true,
processData: true
});
Once the ajax call gets called, it jumps into the controller function but all its properties are NULL. Why is that happening?
BTW: the variable summaryBySource is a global variable that is in the View at the moment that the ajax call is called and it contains the values that matches with the Summary object.
Also, I tried to do the same thing but instead of passing an object, just a dumb string and it also returns null...
Thanks!
EDIT: The content of summaryBySource is
It will be an Object type and...
Total: 0
Average: 0
Issues: 2
Fixed: 1
FixedPercentage: 50
TotalPercentage: 100
IssuesList: Array[1]
0: Object
Name: "Crash"
Code: 1001
I have created a page with a KnockoutJS viewmodel. I want to post the Data to my Server using Web API.
I use this AJAX post:
$.ajax({
url: "/api/blogpost",
contenttype: "application/x-www-form-urlencoded",
data: '=' + encodeURIComponent(ko.toJSON(self.Blog)),
type: "POST",
dataType: "JSON",
timeout: 10000,
success: function (Result) {
},
error: function (xhr, status) {
alert(status + " - " + xhr.responseText);
}
});
To send the JSON data to my Web API method.
This is the JSON that is sent to the server:
{
"BlogTitle": "Sample Post",
"BlogHTML": "<p><strong>Sample JSON Blog Post</strong></p>\n\n<h1><strong>It never works :( </strong></h1>\n",
"BlogThumbnail": "http://mysystemURL/SamplePost/What.jpg",
"BlogSummary": "This is a sample post",
"BlogFQURL": "Sample_Post",
"BlogTags": [
"json",
"devlopment",
"newtag",
""
],
"BlogCategory": 1
}
My WEB API method received the JSON data correctly. The RAW string value looks like this:
"{\"BlogTitle\":\"Sample Post\",\"BlogHTML\":\"<p><strong>Sample JSON Blog Post</strong></p>\\n\\n<h1><strong>It never Works :(</strong></h1>\\n\",\"BlogThumbnail\":\"http://mysystemURL/SamplePost/What.jpg\",\"BlogSummary\":\"This is a sample post\",\"BlogFQURL\":\"Sample_Post\",\"BlogTags\":\"[\\\"json\\\",\\\"devlopment\\\",\\\"newtag\\\",\\\"\\\"]\",\"BlogCategory\":1}"
when I use the JSON visulizer on my data I get this:
I use this BlogPost vari = JsonConvert.DeserializeObject<BlogPost>(value); to deserialize my object but everything stays null
My BlogPost Object looks like this:
public class BlogPost
{
public int BlogPostID { get; set; }
public string BlogPostTitle { get; set; }
public string BlogPostHTML { get; set; }
public string BlogPostThumbnailURL { get; set; }
public string BlogPostSummary { get; set; }
public string BlogPostFQURL { get; set; }
public int BlogPostCategory { get; set; }
public List<TagDTO> BlogPostTags { get; set; }
}
I am really stumped.. Any help would be greatly appreciated!
Your property names don't match. The C# object's properties are BlogPost* and the JSON has Blog*, without the Post.
Correct the names either on the Javascript or on the C# side or use the JsonProperty attribute to specify the name of the serialized property.
There is a similar question with the same title, but the solution is not valid for my problem.
I'm trying to serialize the following JSON:
{"Id":1,
"Questions":
[{"Id":"q-1-Q0001","Text":"Volume Too High"},
{"Id":"q-1-Q0002","Text":"Volume Too Low"}],
"Text":"My text."}
With this structure in my C#:
public class Issue
{
public Issue() { Questions = new List<Question>(); }
public string Id { get; set; }
public List<Question> Questions { get; set; }
public string Text { get; set; }
}
public class Question
{
public string Id { get; set; }
public string Text { get; set; }
}
I have JavaScript send a POST with the JSON above to this C# function:
public JsonResult AddIssueToQueue(Issue issue)
{
var id = issue.Id; // Set correctly
var text = issue.Text; // Set correctly
var q = issue.Questions; // NOT set correctly. Set to List of two empty Question items.
}
id and text are set correctly, but q is set to a List that contains two empty Question objects (Id and Text are null in each).
Is my JSON formatted incorrectly? Why doesn't the Questions array propagate correctly?
This is a just a wild guess, but your JSON structure has an ID with an integer, as rsbarro mentioned above. But your proxy class in C# is expecting a string - is it possible the type conversion is getting mixed up there?
This my ajax call and it is working fine I am getting the question List
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: "{'issue':{'Id':1,'Questions':[{'Id':'q-1-Q0001','Text':'Volume Too High'},{'Id':'q-1-Q0002','Text':'Volume Too Low'}],'Text':'My text.'}}" ,
dataType: 'html',
url: 'AddIssueToQueue',
success: function (data) {
if (data) {
//Do something
}
}
});
Can you share your code as well.