无法使用AJAX将JSON数据传递给MVC控制器
本文关键字:MVC 控制器 数据 JSON AJAX | 更新日期: 2023-09-27 18:18:18
在我的QUIZ应用程序中,我想发送一个对象数组(其中一个问题有四个答案& &;一个正确的答案作为一个对象的属性)给MVC控制器,但它发送空值。解决该问题的关键是对JSON对象进行字符串化,定义模型,并将参数作为定义的模型获取。是否有其他解决方案?
我的视图UI是这样的
//视图脚本<script>
$(document).ready(function () {
$("#btnsubmit").click(function () {
createquestions();
});
function createquestions()
{
var things = [];
var nofques = $("#ddlnofquestions").val();//Coming from Dropdown Value
for (var i = 1; i <= nofques; i++) {
var obj = {
id: i,
question: CKEDITOR.instances[i.toString()].getData(),
answer1:$("#" + i + 1).val(),
answer2: $("#" + i + 2).val(),
answer3: $("#" + i + 3).val(),
answer4: $("#" + i + 4).val(),
correctanswer: $("#" + i + 5).val(),
};
things.push(obj);
}
var thingss = JSON.stringify({ "things": things });
$.ajax({
type: 'POST',
url:'Question/CreateQuestion',
async:true,
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: { things: JSON.stringify(things) },
traditonal: true,
success: function (data) {
alert("Sucessfully Created");
},
});
}
});
</script>
c#: Model Class
public class CreateQuestion
{
public int id { get; set; }
public string question { get; set; }
public string answer1 { get; set; }
public string answer2 { get; set; }
public string answer3 { get; set; }
public string answer4 { get; set; }
public string correctanswer { get; set; }
}
c#:控制器
public ActionResult CreateQuestion(List<CreateQuestion> things)
{
//where we try to get an array of objects
//Working Code......
return View();
}
尝试在AJAX调用中更改:
data: { things: JSON.stringify(things) },
:
data: JSON.stringify(things),
我认为正在发生的事情是,该操作期望对象列表,但在AJAX调用中,您正在发送一个包含对象数组的对象。
您可以尝试这样做:
[HttpPost]public JsonResult CreateQuestion(POCOthings)
其中POCOthings是适合由mvc模型绑定器转换的POCO对象。对于您的案例,您的CreateQuestions列表应该是上述对象的一个字段。
有几点需要检查
- 是404错误吗?
- 是JSON.stringify(事物)一个有效的对象?
- 您可以尝试删除数据类型吗?你正在返回视图,但它期望的数据类型是json。
数据类型:json,