繁体   English   中英

无法使用 AJAX 将 JSON 数据传递给 MVC 控制器?

[英]Unable to pass JSON Data to MVC Controller using AJAX?

在我的 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#:模型类

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 列表应该是所述对象的一个​​字段。 希望能帮助到你。

要检查的东西很少。

  1. 是404错误吗? 操作缺少 httppost 属性。
  2. JSON.stringify(things) 是一个有效的对象吗?
  3. 你可以尝试删除数据类型吗? 您正在返回视图,但它期望的数据类型是 json。

数据类型:'json',

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM