首页 > 解决方案 > JQUERY ajax 将 JSON 发布到 C# MVC 控制器,但传入的数据为空

问题描述

我有一个奇怪的问题。我有一个包含两个类的 C# 数据结构:

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
}

javascript 生成 javascript 对象(对于数据结构来说看起来不错),并且 JSON.stringify 转换为以下 json 字符串:

{"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"}]}

json 数据由以下 jquery 命令发送:

$.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]);
                    }
                }
            });

在 C# 方面,我有以下方法来接收发布数据:

[HttpPost]
    public async Task<string> Add([FromBody] AddQuestionModel2 q)
    {
        var ctx = this.HttpContext;
        JsonResultModel res = new JsonResultModel();
    }

参数“q”始终为空。如果我展开 ctx (HttpContext),Request.Form 数据会抛出 System.InvalidOperationException。

如果你有任何想法可能是错的吗?最大的问题是我无法调试 HttpContext 中发生的事情以及它抛出异常的原因。

提前致谢!嘉宝

标签: c#jqueryjsonajaxasp.net-mvc

解决方案


在您的 ajax 代码中尝试使用 data:data,而不是 data:JSON.stringify(data)。JSON.stringify() 方法将 JavaScript 对象或值转换为 JSON 字符串,但 ajax 数据需要 JavaScript 对象。在布尔字段中使用“true”或“false”代替 0 或 1 来尝试的另一件事。

在邮递员中,一切正常。


推荐阅读