【问题标题】:JQUERY ajax posts JSON to C# MVC controller, but the incoming data is nullJQUERY ajax 将 JSON 发布到 C# MVC 控制器,但传入的数据为空
【发布时间】:2021-02-20 04:22:21
【问题描述】:

我有一个奇怪的问题。我有一个包含两个类的 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#端,我有以下方法来接收post数据:

[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 中发生的事情以及它抛出异常的原因。

提前致谢! 嘉柏

【问题讨论】:

  • 我添加了 QuestionType 的定义。它是一个枚举,所以在客户端它是作为数字管理的。 IsRight 是类中的布尔值,在客户端它是 1 或 0。

标签: c# jquery json ajax asp.net-mvc


【解决方案1】:

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

在邮递员中一切正常。

【讨论】:

  • 我尝试使用数据:数据。结果相同。也尝试了真/假。结果相同。
  • 你是对的。 C# 不能将 0 和 1 转换为 false 和 true。我不得不使用纯 javascript true 和 false。由于字符串“true”和“false”也不被接受。我还必须将 Type 的值从字符串转换为整数,因为 C# 无法自动将“0”转换为 0。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 2016-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多