2012-05-24 72 views
1

我得到在控制器的空值時,我使用jquery AJAXAJAX jquery的傳遞null值

控制器

[HttpPost] 
     public ActionResult UpdateAnswers(string answers, string question, string controlid, int eventid) 
     { 
      var replacetext=string.Empty; 
      if (answers.Length>0) 
      replacetext = answers.Replace("\n", ","); 
      _service.UpdateAnswers(eventid, replacetext, controlid); 
      return PartialView("CustomizedQuestions"); 
     } 

Jquery的處理請求 - Ajax代碼

var test = "{ answers: '" + $("#answerlist").val() + "', question: '" + title + "', controlid: '" + controlid + "', eventid: '" + eventid + "' }"; 
         $.ajax({ 
          url: '@Url.Action("UpdateAnswers")',         
          type: 'POST', 
          dataType: 'html', 
          contentType: 'application/html; charset=utf-8', 
          context: $(this), 
          // data: "{ answers: '"+$("#answerlist").val()+"' ,question: '"+ title +"', controlid:'"+ controlid +"',eventid:'"+ eventid+"'}", 
          data: JSON.stringify(test), 
          success: function (result) { 
           $(this).dialog("close"); 
          }, 
          error: function() { 
           //xhr, ajaxOptions, thrownError 
           alert('there was a problem saving the new answers, please try again'); 
          } 
         }); 

回答

4

您的contentType是錯誤的。當你通過JSON時,你爲什麼將它設置爲application/html?試試這樣:

var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid }; 
$.ajax({ 
    url: '@Url.Action("UpdateAnswers")',         
    type: 'POST', 
    dataType: 'html', 
    contentType: 'application/json; charset=utf-8', 
    context: $(this), 
    data: JSON.stringify(test), 
    success: function (result) { 
     $(this).dialog("close"); 
    }, 
    error: function() { 
     //xhr, ajaxOptions, thrownError 
     alert('there was a problem saving the new answers, please try again'); 
    } 
}); 

或使用application/x-www-form-urlencoded這是默認的:

var test = { answers: $('#answerlist').val(), question: title, controlid: controlid, eventid: eventid }; 
$.ajax({ 
    url: '@Url.Action("UpdateAnswers")',         
    type: 'POST', 
    dataType: 'html', 
    context: $(this), 
    data: test, 
    success: function (result) { 
     $(this).dialog('close'); 
    }, 
    error: function() { 
     //xhr, ajaxOptions, thrownError 
     alert('there was a problem saving the new answers, please try again'); 
    } 
}); 
+0

非常感謝你。 – user335160