无法使用AJAX将JSON数据传递给MVC控制器?
在我的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();
}
尝试樟宜纳克这对您的AJAX调用:
data: { things: JSON.stringify(things) },
对于这一点:
data: JSON.stringify(things),
我认为正在发生的是,行动期待的对象的列表,但对AJAX调用,您正在发送包含对象数组的对象。
我也这样做,但这两个解决方案也没有用。 非常感谢您给出解决方案 –
你可以试试这样做:
[HttpPost] 公共JsonResult CreateQuestion(POCOthings)
凡POCOthings是POCO OBJET适合由MVC模式的粘合剂转化。 对于您的情况,CreateQuestions的列表应该是所述对象的字段。 希望它有帮助。
我已经尝试过您的解决方案,但它给出了相同的响应,即空值 –
很少有事情要检查。
- 是404错误?缺少行动的httppost属性。
- 是JSON.stringify(东西)一个有效的对象?
- 你可以尝试删除dataType吗?你正在返回视图,但它期望的数据类型是json。
数据类型: 'JSON',
我觉得这是一个相当不错的解决方案。也许你的问题更适合http://codereview.stackexchange.com – venerik