JsonConvert.DeserializeObject<T>(value) does not deserialize the object assigned - c#

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.

Related

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 Core http post [FromBody] broken in 3.1, used to work in 2.2

I am having all kinds of errors migrating from ASP.NET Core 2.2, to 3.1.
My latest error is that the object I am receiving via a Http Post is null.
Here is the code that receives the object, and in this case the model is null.
[HttpPost]
public async Task<IActionResult> MyAction([FromBody] BoardMoveModel model)
The model class:
public class BoardMoveModel
{
public int BoardId { get; set; }
public int TicketId { get; set; }
public int DestinationStatusId { get; set; }
public int SourceStatusId { get; set; }
public IEnumerable<int> SourceStatusList {get; set;}
public IEnumerable<int> DestinationStatusList {get; set;}
}
And the Javascript code:
var data = {
TicketId: el.id,
DestinationStatusId: targetStatusId,
SourceStatusId: sourceStatusId,
SourceStatusList: sourceList,
DestinationStatusList: destList
};
$.ajax({
async: true,
url: "/Area/Board/MyAction",
type: "POST",
contentType: "application/json; charset=utf-8",
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(data)
}).done(function(result) {
Here is the actual JSON Payload:
{
"TicketId":"150",
"DestinationStatusId":"5",
"SourceStatusId":"6",
"SourceStatusList":[],
"DestinationStatusList":["140","150"]
}
Model is null because it's invalid for binding. In JSON you are passing in string values while model requires integers. Change either to match and it should work. Binding is by default case sensitive, but it shouldn't be a problem with code you've provided.
Try sending this as application/json body
{
"TicketId":150,
"DestinationStatusId":5,
"SourceStatusId":6,
"SourceStatusList":[],
"DestinationStatusList":[140,150]
}

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.

using json to object binding in asp.net mvc2

I am trying to bind a JSON stringified object to a model and few other strings in the controller and it is not working.
is it not possible,
$.ajax({
url: "/SrcManager/AddDataSource",
type: "POST",
data: JSON.stringify({
content: ct,
dataSourceName: $("#dataSrcName").val(),
parameters: parametersCollection,
sourceContentId: sourceContentId,
sourceId: null,
type: contType
}),
success: function (data) {
if (data.length > 1)
{
alert("DataSource Saved Successfully");
$("#dataSrcId").val(data);
}
}
});
and var parametersCollection = [];
function IPParameters(paramName, paramValue) {
this.ParamName = paramName;
this.ParamValue = paramValue; }
*** action method : public string AddDataSource(ContentModel scvm){.........}
Why does the above not work. Is this not supported or any mistake in the code, kindly suggest the right way.
In the ContentModel, i map the parameters to List<Parameters>.
I have added the JsonValueProviderFactory also in global.asax.
The C# model is :
public class SourceContentViewModel
{
public string sourceId { get; set; }
public string dataSourceName { get; set; }
public string sourceContentId { get; set; }
public string content { get; set; }
public string type { get; set; }
public List<Parameters> parameters { get; set; }
public SourceContentViewModel()
{
parameters = new List<Parameters>();
}
}
public class Parameters
{
public string ParamName { get; set; }
public string ParamValue { get; set; }
}
You can't send JSON to an ASP.NET MVC 2 application as there is no JSON provider factory out-of-the-box that will allow you to read the request. It is built in ASP.NET MVC 3. You may take a look at the following blog post and include the JsonValueProviderFactory discussed there. Then you will be able to send JSON requests to your ASP.NET MVC 2 controller actions after registering it:
protected void Application_Start()
{
RegisterRoutes(RouteTable.Routes);
ValueProviderFactories.Factories.Add(new JsonValueProviderFactory());
}
Also notice the contentType: 'application/json; charset=utf-8' setting when sending the request which instructs the binder that you are sending a JSON request.

JavaScriptSerializer on JSON containing an array

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.

Categories

Resources