在我的QUIZ应用程序中,我想向MVC控制器发送一个对象数组(其中一个问题有四个答案,作为对象属性的一个正确答案),但它发送空值。解决此问题的关键是将JSON对象串联起来,定义一个模型并将参数作为定义的模型。有没有其他解决方案?无法使用AJAX将JSON数据传递给MVC控制器?
我查看UI看起来像this
//视图脚本
<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#:模型类
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();
}
我觉得这是一个相当不错的解决方案。也许你的问题更适合http://codereview.stackexchange.com – venerik