2015-10-19 145 views
-1

在我的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();  
} 
+2

我觉得这是一个相当不错的解决方案。也许你的问题更适合http://codereview.stackexchange.com – venerik

回答

1

尝试樟宜纳克这对您的AJAX调用:

data: { things: JSON.stringify(things) }, 

对于这一点:

data: JSON.stringify(things), 

我认为正在发生的是,行动期待的对象的列表,但对AJAX调用,您正在发送包含对象数组的对象。

+0

我也这样做,但这两个解决方案也没有用。 非常感谢您给出解决方案 –

0

你可以试试这样做:

[HttpPost] 公共JsonResult CreateQuestion(POCOthings)

凡POCOthings是POCO OBJET适合由MVC模式的粘合剂转化。 对于您的情况,CreateQuestions的列表应该是所述对象的字段。 希望它有帮助。

+0

我已经尝试过您的解决方案,但它给出了相同的响应,即空值 –

0

很少有事情要检查。

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

数据类型: 'JSON',

+0

我已经这三件事,但它仍然显示空值。 非常感谢你给出了很好的解决方案 –

+0

我会尝试同时运行提琴手,检查它的网址,形式身体等 – Kalyan

+0

我已经在做这个kalyan .. –

相关问题