2015-10-19 146 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 .. –

相關問題