2012-12-13 75 views
22

我想弄清楚如何從窗體發送一些信息到Web API操作。這是jQuery的/ AJAX我試圖使用方法:發送JSON對象到Web API

var source = { 
     'ID': 0, 
     'ProductID': $('#ID').val(), 
     'PartNumber': $('#part-number').val(), 
     'VendorID': $('#Vendors').val() 
    } 

    $.ajax({ 
     type: "POST", 
     dataType: "json", 
     url: "/api/PartSourceAPI/", 
     data: JSON.stringify({ model: source }), 
     success: function (data) { 
      alert('success'); 
     }, 
     error: function (error) { 
      jsonValue = jQuery.parseJSON(error.responseText); 
      jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 }); 
     } 
    }); 

這裏是我的模型

public class PartSourceModel 
{ 
    public int ID { get; set; } 
    public int ProductID { get; set; } 
    public int VendorID { get; set; } 
    public string PartNumber { get; set; } 
} 

這是我的看法

<div id="part-sources"> 
    @foreach (SmallHorse.ProductSource source in Model.Sources) 
    { 
     @source.ItemNumber <br /> 
    } 
</div> 
<label>Part Number</label> 
<input type="text" id="part-number" name="part-number" /> 

<input type="submit" id="save-source" name="save-source" value="Add" /> 

這裏是我的控制器操作

// POST api/partsourceapi 
public void Post(PartSourceModel model) 
{ 
    // currently no values are being passed into model param 
} 

我錯過了什麼?現在當我調試並且在ajax請求觸發控制器動作時執行此操作時,沒有任何內容被傳遞到模型參數中。

+0

你沒有'JSON.stringify'嘗試? 'data:{model:source}',或者可能只是'data:source' - jQuery爲你處理轉換... – nnnnnn

+0

是的,我沒有使用JSON.stringify來嘗試它,但那也不起作用。我已經嘗試了所有可能的AJAX方面的組合,但我認爲我在控制器上缺少了一些東西......但我不知道,這純粹是一種猜測。 – Cory

+0

當你說「沒有」被傳入模型參數時,你的意思是實例「model」是否爲null?或者它的值是否爲默認值/空值?如果將模型類型更改爲字符串以獲取原始表示,甚至刪除輸入參數並直接探測Request.Content和Request.Headers屬性以找出服務器正在接收的內容,會發生什麼情況? – Snixtor

回答

27

試試這個:

jQuery的

$('#save-source').click(function (e) { 
     e.preventDefault(); 
     var source = { 
      'ID': 0, 
      //'ProductID': $('#ID').val(), 
      'PartNumber': $('#part-number').val(), 
      //'VendorID': $('#Vendors').val() 
     } 
     $.ajax({ 
      type: "POST", 
      dataType: "json", 
      url: "/api/PartSourceAPI", 
      data: source, 
      success: function (data) { 
       alert(data); 
      }, 
      error: function (error) { 
       jsonValue = jQuery.parseJSON(error.responseText); 
       //jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 }); 
      } 
     }); 
    }); 

控制器

public string Post(PartSourceModel model) 
    { 
     return model.PartNumber; 
    } 

查看

<label>Part Number</label> 
<input type="text" id="part-number" name="part-number" /> 

<input type="submit" id="save-source" name="save-source" value="Add" /> 

現在,當你點擊「Add」你填寫文本框後,controller會吐回了你的PartNumber框中警報寫道。

+1

謝謝!通過改變'data:source'來修正它,所以它將正確綁定到控制器中的'model'參數。我想我必須在我的ajax中包含名稱'model:'才能使其工作。非常感謝! – Cory

+0

在複雜數據格式(默認情況下不能反序列化)的情況下,您需要在服務器端接收json字符串。你的答案可能適用於簡單的數據,但不適用於複雜的數據(這就是搜索哈哈)。雖然你的答案對這個傢伙的問題很有幫助! – Zwik

+0

我發現我必須在我的ajax調用中包含'contentType:'application/json''。爲什麼這個答案不需要它? –

-4

我相信你需要周圍的model報價:

JSON.stringify({ "model": source }) 
+2

在對象文字中,如果屬性名稱是數字文字或有效的標識名稱,則不需要引用屬性名稱。所以'{model:source}'很好。 – nnnnnn

+0

您是否使用過瀏覽器的調試器工具來檢查發送到請求正文中的操作方法的內容? –

+0

Queti,是的,我使用的是提琴手,它表示沒有內容與請求一起發送 – Cory

6

變化:

data: JSON.stringify({ model: source }) 

要:

data: {model: JSON.stringify(source)} 

而在你的控制器,你這樣做:

public void PartSourceAPI(string model) 
{ 
     System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer(); 

    var result = js.Deserialize<PartSourceModel>(model); 
} 

如果您在jQuery中使用的URL是/api/PartSourceAPI則控制器名稱必須是api和動作(方法)應該是PartSourceAPI

+0

我試過了,不幸的是它沒有任何區別。 – Cory

+0

看到我修改的答案。 – Jeroen

3
var model = JSON.stringify({ 
    'ID': 0, 
    'ProductID': $('#ID').val(), 
    'PartNumber': $('#part-number').val(), 
    'VendorID': $('#Vendors').val() 
}) 

$.ajax({ 
    type: "POST", 
    dataType: "json", 
    contentType: "application/json", 
    url: "/api/PartSourceAPI/", 
    data: model, 
    success: function (data) { 
     alert('success'); 
    }, 
    error: function (error) { 
     jsonValue = jQuery.parseJSON(error.responseText); 
     jError('An error has occurred while saving the new part source: ' + jsonValue, { TimeShown: 3000 }); 
    } 
}); 

var model = JSON.stringify({  'ID': 0,  ...': 5,  'PartNumber': 6,  'VendorID': 7 }) // output is "{"ID":0,"ProductID":5,"PartNumber":6,"VendorID":7}" 

數據是這樣的 「{」 模型 「: 」ID「:0,」 產品ID 「:6中,」 部分號碼 「:7,」 廠商ID 「:8}}」 網頁API控制器不能綁定到你的模型