2015-05-07 25 views
0
工作

所以我有一個基本的控制器接受後..MVC的jQuery Ajax的帖子 - 只能讓它使用硬編碼值

[HttpPost] 
    public ActionResult Submit(string postCost) 
    { 
     //Do stuff here before sending back redirect details... 

     return Json(new { result = "Redirect", url = Url.Action("Index", "Confirm") }); 
    } 

而且我通過jQuery AJAX方法發佈:

$.ajax({ 
    url: partyURL, 
    dataType: 'json', 
    contentType: 'application/json', //charset=utf-8', 
    type: 'POST', 
    data: { postCost: postageCost}, //**This fails!** 
    //data: "{'postCost':'3.50'}", //**This works** 
    success: function (response) { 

     if (response.result == 'SoldOut') { 
      $("#soldOut").show(); 
     } 
     else if (response.result == 'Redirect') { 
      //All good, onward to confirmation page 
      window.location = response.url; 
     } 
    }, 
    error: function (xhr, status, error) { 
     // Error handling here 
    } 
}); 

其中postageCost變量在失敗時返回狀態500發送:

postageCost = '3.50'; 
postageCost = JSON.stringify(postageCost); //also fails with this 

但如果我硬編碼數據定義一個s

data: "{'postCost':'3.50'}", 

它工作正常。

因此,關鍵在於我在處理數據元素?

+0

檢查返回的錯誤網絡選項卡。 (並且你有沒有試過'data:JSON.stringify({postCost:postageCost}),' –

+0

@StephenMuecke - data:JSON.stringify({postCost:postageCost})如果你發佈答案,你可以有糖果。謝謝:) –

+0

厄齊爾剛剛發佈了一個答案,所以你可以接受(儘管你不需要'postCost'周圍的引號)。作爲一個方面說明,爲什麼你的方法參數不是'(小數postCost)'? –

回答

2

你需要做的

var datum = {'postCost': '3.50'}; 
data: JSON.stringify(datum), //Ajax call data 
+0

謝謝厄齊爾:)我還沒意識到你可以在數據段中串聯。 –