Gabor Varga
Gabor Varga

Reputation: 105

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

Upvotes: 1

Views: 721

Answers (1)

Serge
Serge

Reputation: 43959

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.

Upvotes: 1

Related Questions