【发布时间】: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